我有一个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;
当我运行nodemon时,/something-cool
的api路由有效,但是当我下次运行时,它返回404错误。我在做什么错,该如何解决?
答案 0 :(得分:0)
您正在Next.js之上使用自定义服务器(快速)来自定义路由。这意味着,首先,您必须构建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。