英文:
How to run a Next.js project on a specific port?
问题
这是server.js
文件的内容:
const express = require("express");
const path = require("path");
const next = require("next");
const dev = false;
const app = next({ dev });
const handle = app.getRequestHandler();
app
.prepare()
.then(() => {
const server = express();
// requests to /service-worker.js
server.get(
"/service-worker.js",
express.static(path.join(__dirname, ".next"))
);
// all other requests
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(3002, (err) => { // this
if (err) throw err;
console.log("> Ready on http://localhost:3002"); // this
});
})
.catch((ex) => {
console.error(ex.stack);
process.exit(1);
});
如我所标记的,我正在使用端口3002
运行项目。但在运行forever start server.js
后,仍然无法访问http://<ip>:3002
。
另外,当我在项目的根目录运行yarn start
时,它显示:
端口3000已被占用。
为什么它不关心我在server.js
中指定的端口?
英文:
Here is the content of server.js
file:
const express = require("express");
const path = require("path");
const next = require("next");
const dev = false;
const app = next({ dev });
const handle = app.getRequestHandler();
app
.prepare()
.then(() => {
const server = express();
// requests to /service-worker.js
server.get(
"/service-worker.js",
express.static(path.join(__dirname, ".next"))
);
// all other requests
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(3002, (err) => { // this
if (err) throw err;
console.log("> Ready on http://localhost:3002"); // this
});
})
.catch((ex) => {
console.error(ex.stack);
process.exit(1);
});
As I've highlighted, I'm running the project on port 3002
. But after running forever start server.js
, still http://<ip>:3002
is not reachable.
Also, when I run yarn start
on the root of the project, it says:
> Port 3000 is already in use.
Why it doesn't care about the port I specified inside server.js
?
答案1
得分: 2
正如我所强调的,我正在使用3002端口运行项目
你所做的并不是这样,你只是让你的服务器监听在3002端口,但当你运行yarn start
时,项目将在默认端口3000上启动。
你可以在你的package.json
文件中这样更改它:
"scripts": {
//...
"dev": "next dev -p 3002",
"start": "next start -p 3002",
},
你还需要检查服务器是否正在监听该端口(lsof | grep -i PORT
),然后在防火墙上启用访问,使用以下命令来在防火墙上启用访问:
sudo ufw allow 3002/tcp
只需确保 ufw 已安装并正确设置。
英文:
>As I've highlighted, I'm running the project on port 3002
That's not what you did, you just made your server listening on PORT 3002 but when you run yarn start
the project will start on the default port 3000
you can change it this way in your package.json
file:
"scripts": {
//...
"dev": "next dev -p 3002",
"start": "next start -p 3002",
},
You also need to check if the port itself is listening on the server(lsof | grep -i PORT
) and then enable access on the firewall, use the following command to enable access in the firewall:
sudo ufw allow 3002/tcp
Just make sure ufw is installed & properly setup.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论