Node.js+Express+Vite项目POST请求返回404求助
问题
我是Node.js、Express和Vite的新手,正在学习Node.js配置,参与了一个Glitch上使用Vite的挑战项目。编写server.js代码后,添加的POST接口无论是通过Postman测试还是React应用调用,都持续返回404错误。
相关代码
server.js
// server.js // init project import express, { json, urlencoded } from 'express' import morgan from 'morgan' import { join } from 'path' import { santaController } from './src/server/controllers/santa-controller.js' import { apiConfig } from './config/api-config.js' import { emailSender } from './src/server/services/email-sender.js' // Starting up express const app = express() // Middleware app.use(morgan(':method :url :status :res[content-length] - :response-time ms')) app.use(express.json()) app.use(urlencoded({ extended: false })) app.use(express.static('public')) app.post('/api', (req, res) => { res.send('hello') }) app.post(apiConfig.WISH_API.POST_WISH, async (request, response) => { try { const { user, userAddress, wish } = request.body const wishId = await santaController.postWish(user, userAddress, wish) // Send the generated wish ID as a response response.send({ wishId }) } catch (e) { console.error('Failed to post wish:', e) response.status(500).json({ error: 'Failed to post wish' }) } }) app.get('/', (request, response) => { response.sendFile(join(__dirname, 'dist', 'index.html')) console.log(response.json(routes)) }) // listen for requests :) const listener = app.listen(3000, () => { console.log('Your app is listening on port ' + listener.address().port) // Initialize the email sender emailSender.initEmailSender() })
API配置文件
// Storing Fetch API URLs in a config file for maintainability const BASE_PATH = `/api` const API_VER = `/v1` export const apiConfig = { WISH_API: { POST_WISH: `${BASE_PATH}${API_VER}/wish`, }, }
React调用代码
// Make a POST request to the wish endpoint const response = await axios.post(apiConfig.WISH_API.POST_WISH, wishData, { headers: {'Content-Type': 'application/json', },});
404错误请求信息
Request URL: http://localhost:3000/api/v1/wish
Request Method: POST
Status Code: 404 Not Found
请求头详情:
Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate, br Accept-Language: ja-JP,ja;q=0.9,en-GB;q=0.8,en;q=0.7,en-US;q=0.6 Connection: keep-alive Content-Length: 174 Content-Type: application/json Dnt: 1 Host: localhost:3000 Origin: http://localhost:3000 Referer: http://localhost:3000/ Sec-Ch-Ua: "Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116" Sec-Ch-Ua-Mobile: ?0 Sec-Ch-Ua-Platform: "Windows" Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-origin User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36
解答
核心问题:Vite开发环境下的请求转发缺失
Vite开发服务器默认会接管所有前端请求,包括你发送的API请求,导致请求没有被转发到Express服务器,直接返回404。同时,Express和Vite默认端口可能冲突,也会加剧这个问题。
修复步骤
- 添加Vite代理配置
在项目根目录创建或修改vite.config.js,添加代理规则将API请求转发到Express服务器:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], server: { proxy: { '/api': { target: 'http://localhost:3000', changeOrigin: true } }, port: 5173 // 用Vite默认端口,避免和Express的3000端口冲突 } })
- 分别启动服务
- 先启动Express服务器:执行
node server.js,确认控制台输出Your app is listening on port 3000 - 再启动Vite开发服务器:执行
npm run dev,前端应用会运行在http://localhost:5173
- 验证接口
- 用Postman请求
http://localhost:5173/api(POST方法),应该返回"hello" - React中的Axios请求无需修改,代理会自动把
/api开头的请求转发到Express服务器
额外优化点
- 移除
app.get('/')中的console.log(response.json(routes))代码:routes变量未定义,会导致服务器报错,影响接口正常响应 - 确保Express的路由路径和
apiConfig中的拼接结果完全一致,当前/api/v1/wish的配置是正确的
内容的提问来源于stack exchange,提问作者fortylines
相关产品推荐
相关产品推荐

