You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express+MongoDB项目本地正常,部署至Vercel出现404错误求助

核心问题:Express+MongoDB项目本地运行正常,部署至Vercel后出现404错误

我是开发新手,这个问题已经困扰我三周了,麻烦各位帮忙看看!

已执行的操作

  • 查阅Express和Vercel官方文档
  • 将index.js移入api文件夹
  • 创建了vercel.json文件(不确定其中代码是否正确)
  • 检查了package.json中的scripts与start命令
  • 更新仓库至少5次以尝试让Vercel正常运行

api文件夹中的index.js代码

const express = require('express');
const mongoose = require('mongoose');
const Blog = require('../models/blog');
const { render } = require('ejs');
const { v4 } = require('uuid');

// express app
const app = express();

// connect to MongoDB
const dbURI = 'mongodb+srv://USER:PASSWORD@clusterXXX.mongodb.net/?retryWrites=true&w=majority';
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true})
    .then((request) => {
        // listen to request
        app.listen(3000);
        console.log('Connected to DB');
    })
    .catch((err) => {
        console.log(err);
    });

app.get('/api', (req, res) => {
    const path = `/api/item/${v4()}`;
    res.setHeader('Content-Type', 'text/html');
    res.setHeader('Cache-Control', 's-max-age=1, stale-while-revalidate');
    res.end(`Hello! Go to item: <a href="${path}">${path}</a>`);
    });
    
    app.get('/api/item/:slug', (req, res) => {
    const { slug } = req.params;
    res.end(`Item: ${slug}`);
    });

// To create view engine:
app.set('view engine', 'ejs');

// static file of style.css with the foldername of public
app.use(express.static('public'));

// Creating an express server
app.get('/', (req, res) => {
    res.redirect('/blogs')
    
});

app.get('/about', (req, res) => {
    res.render('about', { title: 'Rules'});
});

app.get('/blogs/create', (req, res) => {
    res.render('create', { title: 'New Confession'});
});

app.get('/blogs', (req, res) => {
    Blog.find().sort({ createdAt: -1 })
        .then((result) => {
            res.render('index', {title: 'All Blogs', blogs: result}) 
        })
        .catch((err) => {
            console.log(err);
        })
});;

app.post('/blogs', (req, res) => {
    const blog = new Blog(req.body);
  
    blog.save()
      .then(result => {
        res.redirect('/blogs');
      })
      .catch(err => {
        console.log(err);
      });
  });

app.get('/blogs/:id', (req, res) => {
    const id = req.params.id;
    Blog.findById(id)
        .then(result => {
            res.render('details', { blog: result, title: 'Blog Details' });
        })
        .catch(err => {
            console.log(err);
        })
});

app.use((req, res) => {
    res.status(404).render('404', { title: 'Page not found'});
});

module.exports = app;

package.json文件代码

{
  "name": "confessay",
  "version": "1.0.0",
  "description": "Deploy express app to vercel",
  "main": "./api/index.js",
  "scripts": {
    "start": "nodemon index"
  },
  "author": "Dun Yan",
  "license": "ISC",
  "dependencies": {
    "ejs": "^3.1.8",
    "express": "^4.18.2",
    "lodash": "^4.17.21",
    "mongoose": "^6.7.0",
    "morgan": "^1.10.0",
    "uuid": "^9.0.0"
  }
}

vercel.json文件代码

{
  "version": 2,
  "builds": [
    {
      "src": "./index.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/"
    }
  ],
  "rewrites": [{ "source": "/api/(.*)", "destination": "/api" }]
}

我曾尝试移除vercel.json中的如下代码片段,但问题仍未解决:

"rewrites": [{ "source": "/api/(.*)", "destination": "/api" }]

内容的提问来源于stack exchange,提问作者Dun Yann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 21:25:19