在 Next.js 应用程序中找不到 API 路由(找不到页面)

Dya*_*len 5 javascript api reactjs server-side-rendering next.js

我正在使用 Next.js 应用程序,并且创建了一个api 路由来发送电子邮件。

一切都在我的开发环境中工作。

但是,当我部署到生产环境时,我只收到一个404-The page could not be found错误作为对此 api 路由的响应。

我不是项目的创建者,我怀疑问题出在用于部署的 npm 命令中。

我刚刚在 'pages/api' 中创建了一个文件,并将其包含server.post('*', (req, res) => handle(req, res));在 server.js 文件中。我还需要做什么吗?

我正在使用 Vercel 进行部署。

这些是我在package.json文件中的脚本:

"scripts": {
    "dev": "node index.js",
    "build": "NODE_ENV=production next build",
    "start": "node index.js",
    "export": "next export",
    "now-build": "next build && next export -o dist"
}
Run Code Online (Sandbox Code Playgroud)

在本地环境中,我正在使用npm start命令。

我在生产中的构建命令是 npm run now-build

在此处输入图片说明

这是index.js文件:

"scripts": {
    "dev": "node index.js",
    "build": "NODE_ENV=production next build",
    "start": "node index.js",
    "export": "next export",
    "now-build": "next build && next export -o dist"
}
Run Code Online (Sandbox Code Playgroud)

这是server.js文件:

const { setConfig } = require('next/config')
setConfig(require('./next.config'))

require('./server')
Run Code Online (Sandbox Code Playgroud)

这是我的 api 路由文件pages/api/send-email.js

const express = require('express');
const next = require('next');
const nextI18NextMiddleware = require('next-i18next/middleware').default;

const nextI18next = require('./i18n');

const port = process.env.PORT || 3007;
const app = next({ dev: process.env.NODE_ENV !== 'production' });
const handle = app.getRequestHandler();

(async () => {
  await app.prepare();
  const server = express();

  server.post('*', (req, res) => handle(req, res));

  server.use(nextI18NextMiddleware(nextI18next));

  server.get('*', (req, res) => handle(req, res));

  await server.listen(port);
  console.log(`> Ready on http://localhost:${port}`); // eslint-disable-line no-console
})();
Run Code Online (Sandbox Code Playgroud)

这就是我调用 api 路由的方式:

import sendEmail from '../../utils/sendEmail';

export default async (req, res) => {
  if (req.method === 'POST') {
    const { to, subject, html } = req.body;
    const response = await sendEmail({ to, subject, html });
    if (response.success) {
      return res.status(200).end();
    }
    return res.status(500).json(response);
  }
  return res.status(400).end();
};
Run Code Online (Sandbox Code Playgroud)

这是我的next.config.js文件:

    fetch('/api/send-email', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        to: formEmailTo,
        subject: formEmailSubject,
        html: FormEmailContent
      })
    })
      .then((response) => {
        if (!response.ok) {
          throw Error(response.statusText);
        }
        return response;
      })
      .then(() => handleOpenSnackbarMsg())
      .catch(() => handleOpenSnackbarErrMsg());
Run Code Online (Sandbox Code Playgroud)

谢谢!

小智 3

如果您的项目包含 API 路由,则无法使用下一个导出。next export从......中去除"now-build": "next build && next export -o dist"

参考: https: //nextjs.org/docs/api-routes/introduction#caveats