您好,我目前正在尝试在 Vercel 上部署我的 MERN 应用程序的后端..
在这次尝试之前,我通过小型 todo 项目学会了在 vercel 上部署 meern 站点。我现在工作得很好,我对下面的项目也做了同样的事情。但它显示 404 错误
这是我的package.json
{
"name": "backend",
"version": "1.0.0",
"description": "simple mern note taking application for open ended assignment",
"main": "server.js",
"engines": {
"node": "20.x"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon server.js"
},
"author": "baos sora",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.3",
"mongodb": "^6.5.0",
"mongoose": "^8.2.3",
"node-cron": "^3.0.3",
"nodemon": "^3.1.0"
}
}
这是我的 vercel.json
{
"version": 2,
"builds": [{
"src": "./server.js",
"use": "@vercel/node"
}],
"routes": [
{ "src": "/(.*)", "dest": "/" }
]
}
这是我的环境
URL=worked url from mongodb
PORT=3000
这是我的server.js
//import required modules
const express = require('express');
require('dotenv').config();
const mongoose = require('mongoose');
const cors = require('cors');
const NoteRoutes = require('./routes/noteRoutes')
const { getCategory, deleteCategory, getOneCategryData } = require('./controller/categoryController')
const { getDynamicNoteData, DeleteInActiveNotes, AutoHardDeleteNotes } = require('./controller/noteController')
//initialize express app
const app = express();
// Middleware to parse incoming requests with JSON
app.use(express.json())
//middleware to handle cors policy
app.use(cors());
app.get('/', (req, res) => {
res.json({ message: 'Welcome to Note API' })
})
app.use('/note', NoteRoutes)
//manually create routes because of casting issues
app.get('/search', getDynamicNoteData)
app.delete('/remove', DeleteInActiveNotes)
app.get('/category', getCategory)
app.get('/category/:id', getOneCategryData)
app.delete('/category/:id', deleteCategory)
const PORT = process.env.PORT || 5000;
const URL = process.env.URL;
//establish connection to mongodb database using mongoose
mongoose.connect(URL)
//if connection success display the success messages
.then(() => {
console.log("Connected with MongoDB");
//call auto deletion function
AutoHardDeleteNotes()
//app listning port
app.listen(PORT, () => {
console.log("Server is running on port " + PORT);
})
})
//if there is a error on connecting show display the error message
.catch(err => {
console.log("Application has Following Errors: \n" + err);
})
这是我部署项目时显示的
请帮我找到这个问题。这是我的实习第二轮开放式作业,截止日期将于明天结束。直到今天我只使用netlify。但他们的指导方针说需要添加 vercel。
根据 Vercel 指南 部署 Express 服务器。
Create a directory named /api.
Inside /api, create a file named index.ts. This will be your main server file.
您需要在根级别创建一个 /api 文件夹,并将 server.js 重命名为 index.js,然后将文件移动到 /api 文件夹。
希望这有帮助!