乐闻世界logo
搜索文章和话题

Nextjs 项目如何设置运行端口?

7 个月前提问
3 个月前修改
浏览次数233

6个答案

1
2
3
4
5
6

在 Next.js 中,可以通过两种主要方式设置应用的端口:

1. 使用命令行参数

你可以在启动 Next.js 应用时,通过命令行指定端口。默认情况下,Next.js 应用会在端口 3000 上运行。但如果你想改变端口,可以在 npm run dev 或者 yarn dev 命令后面添加 -p 参数,后跟你希望使用的端口号。例如,如果你想在端口 5000 上运行应用,可以这样操作:

bash
npm run dev -p 5000 # 或者 yarn dev -p 5000

2. 在代码中设置

如果你需要在代码层面配置端口,你可以在 Next.js 自定义服务器的脚本中这样做。例如,如果你使用的是 Express.js 作为自定义服务器,你可以在 server.js 文件中设置端口,如下所示:

javascript
const express = require('express'); const next = require('next'); const port = parseInt(process.env.PORT, 10) || 5000; const dev = process.env.NODE_ENV !== 'production'; const app = next({ dev }); const handle = app.getRequestHandler(); app.prepare().then(() => { const server = express(); server.all('*', (req, res) => { return handle(req, res); }); server.listen(port, (err) => { if (err) throw err; console.log(`> Ready on http://localhost:${port}`); }); });

在上面的代码示例中,端口号被设置为环境变量 PORT 的值,如果没有指定,则默认为 5000。这样,你可以通过设置环境变量的方式灵活地更改端口号。

环境变量

另外,你还可以通过环境变量文件 .env.local 来设置端口号。但请注意,Next.js 并不直接支持通过环境变量来设置端口号,你需要在自定义服务器代码中读取环境变量来设置端口。

bash
# .env.local 文件 PORT=5000

然后在 server.js 中读取这个环境变量:

javascript
const port = parseInt(process.env.PORT, 10) || 3000;

结论

通常,大多数情况下使用命令行参数来设置端口就足够了,它简单直接。但如果你需要更复杂的配置,或者你的应用已经使用了自定义服务器,你可以在代码中设置端口。记住,对于生产环境部署,端口通常由部署环境决定,例如,许多 PaaS(平台即服务)如 Heroku 或 Vercel 会自动分配端口,你不需要手动设置。

2024年6月29日 12:07 回复

This work for me:

shell
"scripts": { "dev": "next dev -p 8080", "start": "next start -p 8080", },
2024年6月29日 12:07 回复

"scripts": { "dev": "next dev -p 8080", // for dev "start": "next start -p 8080" // for prod },

2024年6月29日 12:07 回复

With yarn, pnpm you can easily pass any arguments:
yarn dev -p 8080 or yarn dev --port=8080

With npm using -- to pass arguments:
npm run dev -- -p 8080

2024年6月29日 12:07 回复

The application will start at http://localhost:3000 by default. The default port can be changed with -p, like so:

shell
npx next dev -p 4000

Or using the PORT environment variable:

shell
PORT=4000 npx next dev

#note that I used npx not npm

You can also set the hostname to be different from the default of 0.0.0.0, this can be useful for making the application available for other devices on the network. The default hostname can be changed with -H, like so:

shell
npx next dev -H 192.168.1.2

If you're getting an error that the port is already in use, what you can do to resolve it on windows is

shell
Go to the Task Manager. Scroll and find a task process named. Node.js: Server-side End this particular task.
2024年6月29日 12:07 回复

just need to do:

shell
yarn dev -p PORT_YOU_LIKE
2024年6月29日 12:07 回复

你的答案