根据 文档,为了对使用 Node 适配器运行的 SvelteKit 应用程序使用自定义端口号,我应该安装
dotenv
,然后将其添加到我的 .env
文件中:
HOST=127.0.0.1 PORT=3003 node build
然后我用以下方法构建我的应用程序:
node -r dotenv/config build
...我看到这个错误:
node:events:492
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND 127.0.0.1 PORT=3003 node build
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:107:26)
Emitted 'error' event on Server instance at:
at GetAddrInfoReqWrap.doListen [as callback] (node:net:2066:12)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:107:17) {
errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: '127.0.0.1 PORT=3003 node build'
如果我忽略这一点并执行常规的
npm build
并将我的构建推送到我的节点服务器,然后尝试使用pm2
启动它:
pm2 start index.js
...它会引发错误,因为端口
3000
(SvelteKit 默认值)正在被我的其他应用程序之一使用。
但是,如果我绕过所有这些恶作剧,并在生产服务器上修改
index.js
以手动更改端口,则该应用程序可以正常工作!
const path = env('SOCKET_PATH', false);
const host = env('HOST', '0.0.0.0');
const port = env('PORT', !path && '3003'); //<-- Manually edit here like a caveman 😬
const server = polka().use(handler);
server.listen({ path, host, port }, () => {
console.log(`Listening on ${path ? path : host + ':' + port}`);
});
export { host, path, port, server };
我做错了什么?当我第一次构建应用程序时,如何让应用程序嵌入自定义端口号?
由于错误提到了这一行:
hostname: '127.0.0.1 PORT=3003 node build'
这意味着节点认为主机名是整个字符串
'127.0.0.1 PORT=3003 node build'
除非我弄错了,
.env
文件应该看起来更像这样:
HOST=127.0.0.1
PORT=3003
所以每个变量都在它自己的行上。它应该只包含变量,所以没有
node
或 build
。