自定义服务器
Next.js 默认使用 next start启动其内置服务器。如果您已有现有的后端,您仍然可以将它与 Next.js 一起使用(这不是自定义服务器)。自定义的 Next.js 服务器允许您以编程方式启动一个用于自定义模式的服务器。大多数情况下,您不需要使用这种方法,除非您需要特殊处理。
您需要知道:
查看以下自定义服务器示例:
import { createServer } from "http";
import { parse } from "url";
import next from "next";
const port = parseInt(process.env.PORT || "3000", 10);
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url!, true);
handle(req, res, parsedUrl);
}).listen(port);
console.log(
`> Server listening at http://localhost:${port} as ${
dev ? "development" : process.env.NODE_ENV
}`
);
});
import { createServer } from "http";
import { parse } from "url";
import next from "next";
const port = parseInt(process.env.PORT || "3000", 10);
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url!, true);
handle(req, res, parsedUrl);
}).listen(port);
console.log(
`> Server listening at http://localhost:${port} as ${
dev ? "development" : process.env.NODE_ENV
}`,
);
});
server.js不会经过 Next.js 的编译器或打包过程。请确保该文件所需的语法和源代码与您使用的 Node.js 版本兼容。查看示例.
要运行自定义服务器,你需要在package.json中更新scripts:
{
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
}
或者,你可以设置 nodemon (示例)。自定义服务器使用以下导入将服务器与 Next.js 应用程序连接:
import next from "next";
const app = next({});
上面的next导入是一个函数,它接收一个包含以下选项的对象:
| Option | Type | Description |
|---|---|---|
conf | Object | The same object you would use in next.config.js. Defaults to {} |
customServer | Boolean | (Optional) Set to false when the server was created by Next.js |
dev | Boolean | (Optional) Whether or not to launch Next.js in dev mode. Defaults to false |
dir | String | (Optional) Location of the Next.js project. Defaults to '.' |
quiet | Boolean | (Optional) Hide error messages containing server information. Defaults to false |
hostname | String | (Optional) The hostname the server is running behind |
port | Number | (Optional) The port the server is running behind |
httpServer | node:http#Server | (Optional) The HTTP Server that Next.js is running behind |
返回的app可用于根据需要让 Next.js 处理请求。