【问题标题】:NextJS throwing 404 when deployed to VercelNextJS 在部署到 Vercel 时抛出 404
【发布时间】:2020-08-17 15:22:28
【问题描述】:

我有一个与 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();

【问题讨论】:

标签: javascript reactjs next.js vercel


【解决方案1】:

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

自定义服务器不能部署在 Vercel 上,Next.js 是为平台而设计的。

来源:Custom Server

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

来源:API Routes

还可以查看本指南,了解如何将自定义 Next.js 服务器转换为路由:

来源:Server to Routes Guide

【讨论】:

    猜你喜欢
    • 2021-04-22
    • 2022-01-02
    • 2021-08-01
    • 2022-10-07
    • 2023-01-18
    • 1970-01-01
    • 2021-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多