在 Next.js 应用程序中找不到 API 路由(找不到页面) [英] API route not found in a Next.js App (The page could not be found)

查看:210
本文介绍了在 Next.js 应用程序中找不到 API 路由(找不到页面)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Next.js 应用程序,并且创建了一个

这是 index.js 文件:

const { setConfig } = require('next/config')setConfig(require('./next.config'))要求('./服务器')

这是 server.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();(异步() => {等待 app.prepare();const server = express();server.post('*', (req, res) => handle(req, res));server.use(nextI18NextMiddleware(nextI18next));server.get('*', (req, res) => handle(req, res));等待 server.listen(port);console.log(`> Ready on http://localhost:${port}`);//eslint-disable-line 无控制台})();

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

从'../../utils/sendEmail'导入sendEmail;导出默认异步(req,res)=>{if (req.method === 'POST') {const { to, subject, html } = req.body;const response = await sendEmail({ to, subject, html });如果(响应.成功){返回 res.status(200).end();}返回 res.status(500).json(response);}返回 res.status(400).end();};

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

 fetch('/api/send-email', {方法:'POST',标头:{'内容类型':'应用程序/json'},正文:JSON.stringify({到:formEmailTo,主题:formEmailSubject,html: 表单电子邮件内容})}).then((响应) => {如果(!响应.确定){抛出错误(response.statusText);}返回响应;}).then(() => handleOpenSnackbarMsg()).catch(() => handleOpenSnackbarErrMsg());

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

const withCSS = require('@zeit/next-css')const withImages = require('next-images');module.exports = withImages(与CSS({exportTrailingSlash: 真,导出路径映射:函数(){返回 {'/': { 页: '/' },'/blank-page': { page: '/blank-page' },};},公共运行时配置:{localeSubpaths: typeof process.env.LOCALE_SUBPATHS === 'string'?process.env.LOCALE_SUBPATHS: '没有任何',},webpack: (config, options) =>{cssModules: 真,//config.module.rules.push({//强制执行: 'pre',//测试:/\.js?$/,//排除:[/node_modules/],//loader: 'eslint-loader',//         选项: {//安静:真的,//}//});配置节点 = {fs: '空'}返回配置;},}));

谢谢!

解决方案

如果您的项目包含 API 路由,则不能使用 next export.从 "now-build" 中删除 next export:"next build &&&&&&&&&&&&&&&&&&&&next export -o dist".

参考:https://nextjs.org/docs/api-routes/introduction#注意事项

I am working in a Next.js app, and I've create an api route to send emails.

Everthing is working in my development environment.

However, when I deployed to production I just receive a 404 - The page could not be found error as response for this api route.

I am not the creator of the project, I suspect the problem is in the npm command used to deploy.

I just created a file in 'pages/api' and include this: server.post('*', (req, res) => handle(req, res)); on the server.js file. Do I need to do anything else?

I am using Vercel to deploy.

These are my scripts in the package.json file:

"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"
}

In local environment I am using npm start command.

My build command in production is npm run now-build

This is the index.js file:

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

require('./server')

This is the server.js file:

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
})();

This is my api route file in pages/api/send-email.js:

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();
};

This is how I am calling the api route:

    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());

This is my next.config.js file:

const withCSS = require('@zeit/next-css')
const withImages = require('next-images');

module.exports = withImages(
  withCSS({
    exportTrailingSlash: true,
    exportPathMap: function() {
      return {
        '/': { page: '/' },
        '/blank-page': { page: '/blank-page' },
      };
    },
    publicRuntimeConfig: {
      localeSubpaths: typeof process.env.LOCALE_SUBPATHS === 'string'
        ? process.env.LOCALE_SUBPATHS
        : 'none',
    },
    webpack: (config, options) => {
      cssModules: true,
      //      config.module.rules.push({
      //          enforce: 'pre',
      //          test: /\.js?$/,
      //          exclude: [/node_modules/],
      //          loader: 'eslint-loader',
      //          options: {
      //            quiet: true,
      //          }
      //      });
      config.node = {
        fs: 'empty'
      }
      return config;
    },
  })
);

Thank you!

解决方案

You cannot use next export if your project contains API routes. Remove next export from "now-build": "next build && next export -o dist".

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

这篇关于在 Next.js 应用程序中找不到 API 路由(找不到页面)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆