0

我有一个 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时的api路由/something-cool有效,但是当我运行下一次运行时,它返回404错误。我做错了什么,我该如何解决?

4

1 回答 1

1

您在 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 。

于 2020-03-03T10:56:12.407 回答