gpt4 book ai didi

javascript - NextJS 在部署到 Vercel 时抛出 404

转载 作者:行者123 更新时间:2023-12-05 06:12:58 35 4
gpt4 key购买 nike

我有一个与 NextJS 一起使用的自定义 express 服务器。

当我在本地开发时一切正常,但是当我部署到 Vercel 时,每当我尝试访问我的后端 API 时我都会捕获 404。

可能出了什么问题?这是我的 server.ts:

import express from 'express';
import next from 'next';
import bodyParser from 'body-parser';
import { connectDbs } from './config/db';
import { listingsRouter } from './routes';

const PORT = process.env.PORT || 3003;
const dbs = ['mydb'];

const dev = process.env.NODE_DEV !== 'production';
const nextApp = next({ dev });
const handle = nextApp.getRequestHandler();

const applyMiddleware = (app) => {
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
};

const applyRoutes = (app) => {
app.use('/api/listings', listingsRouter);
};

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

applyMiddleware(app);
applyRoutes(app);

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

await connectDbs(dbs);

app.listen(PORT, () => console.log(`App listening on port ${PORT}`));
};

startServer();

最佳答案

自定义服务器的 Next.js 文档:

A custom server cannot be deployed on Vercel, the platform Next.js was made for.

来源:Custom Server

即使您无法部署自定义服务器,但通常不需要这样做,因为 Next.js 使用 /pages/api 目录支持无服务器功能。

来源:API Routes

另请参阅本指南,了解如何将自定义 Next.js 服务器转换为路由:

来源:Server to Routes Guide

关于javascript - NextJS 在部署到 Vercel 时抛出 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63453854/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com