【发布时间】:2020-10-21 03:48:28
【问题描述】:
我正在使用 Next.js 应用程序,我创建了一个 api route 来发送电子邮件。
一切都在我的开发环境中运行。
但是,当我部署到生产环境时,我只收到一个 404 - The page could not be found 错误作为此 api 路由的响应。
我不是项目的创建者,我怀疑问题出在用于部署的 npm 命令中。
我刚刚在“pages/api”中创建了一个文件,并在 server.js 文件中包含以下内容:server.post('*', (req, res) => handle(req, res));。我还需要做什么吗?
我正在使用 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"
}
在本地环境中我使用npm start 命令。
我在生产中的构建命令是npm run now-build
这是index.js 文件:
const { setConfig } = require('next/config')
setConfig(require('./next.config'))
require('./server')
这是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();
(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
})();
这是我在pages/api/send-email.js中的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();
};
这就是我调用 api 路由的方式:
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());
这是我的next.config.js 文件:
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;
},
})
);
谢谢!
【问题讨论】:
标签: javascript reactjs api next.js server-side-rendering