Api 生产返回 404
Api returning 404 on production
我有一个 next.js 应用程序,我正在尝试创建一个 api。当我 运行 它作为开发时, api 被调用,但是当我 运行 它使用 next start
时,我在调用 api 时收到 404 错误的。
这是相关的 server.js 代码:
app.prepare().then(() => {
require('./server/startup/routes')(server);
server.get('*', (req, res) => {
return handle(req, res);
});
const PORT = process.env.PORT || 5000;
server.listen(PORT, err => {
if (err) throw err;
console.log(`> Read on http://localhost:${PORT}`);
});
});
这是路由文件
module.exports = app => {
app.use('/api/something-cool', cool);
};
酷文件:
const express = require('express');
const router = express.Router();
router.post('/', async (req, res) => {
...Code
res.send({ status: 'ok' });
});
module.exports = router;
/something-cool
的api路由在我运行nodemon时有效,但是当我运行下一个运行时,它returns一个404 错误。我做错了什么,我该如何解决?
您正在 Next.js 之上使用自定义服务器 (express) 来自定义路由。这意味着首先,您必须构建 Next.js 应用程序,然后您必须 运行 您的 server.js
文件才能为应用程序提供服务。
选项 1:
首先构建生产应用程序
next build
然后运行你server.js
文件:
NODE_ENV=production node server.js
更多信息在这里https://github.com/zeit/next.js/tree/master/examples/custom-server-express
选项 2:
还可以选择在 Next.js 应用程序中创建 API 路由,而无需使用自定义服务器。
有关如何操作的详细信息,请参阅 https://github.com/zeit/next.js/tree/master/examples/api-routes。
我有一个 next.js 应用程序,我正在尝试创建一个 api。当我 运行 它作为开发时, api 被调用,但是当我 运行 它使用 next start
时,我在调用 api 时收到 404 错误的。
这是相关的 server.js 代码:
app.prepare().then(() => {
require('./server/startup/routes')(server);
server.get('*', (req, res) => {
return handle(req, res);
});
const PORT = process.env.PORT || 5000;
server.listen(PORT, err => {
if (err) throw err;
console.log(`> Read on http://localhost:${PORT}`);
});
});
这是路由文件
module.exports = app => {
app.use('/api/something-cool', cool);
};
酷文件:
const express = require('express');
const router = express.Router();
router.post('/', async (req, res) => {
...Code
res.send({ status: 'ok' });
});
module.exports = router;
/something-cool
的api路由在我运行nodemon时有效,但是当我运行下一个运行时,它returns一个404 错误。我做错了什么,我该如何解决?
您正在 Next.js 之上使用自定义服务器 (express) 来自定义路由。这意味着首先,您必须构建 Next.js 应用程序,然后您必须 运行 您的 server.js
文件才能为应用程序提供服务。
选项 1:
首先构建生产应用程序
next build
然后运行你server.js
文件:
NODE_ENV=production node server.js
更多信息在这里https://github.com/zeit/next.js/tree/master/examples/custom-server-express
选项 2:
还可以选择在 Next.js 应用程序中创建 API 路由,而无需使用自定义服务器。
有关如何操作的详细信息,请参阅 https://github.com/zeit/next.js/tree/master/examples/api-routes。