Next.js向Express.js服务器POST请求出现404错误的原因及解决
问题描述
我在Next.js中创建用户注册表单,提交表单数据至Express.js服务器时,POST请求http://localhost:3000/api/register返回404(Not Found)错误。
客户端代码
const onSubmit: SubmitHandler<IFormInput> = async (data) => { try { const response = await fetch('http://localhost:3000/api/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }); if (!response.ok) { throw new Error('Network response was not ok'); } const responseData = await response.json(); console.log(responseData); reset(); } catch (error) { console.error('Error', error); } };
服务端代码
const express = require('express'); const app = express(); require('dotenv').config(); const mongoose = require('mongoose'); const User = require('./user.model'); mongoose.connect(process.env.DB_CONNECTION_STRING) .then(() => console.log('Connected to database')) .catch(err => console.log(err)); app.use(express.json()); app.post('/api/register', async (req, res) => { const userData = req.body; //Create a user in database const user = new User(userData); await user.save(); res.json({ message: 'User registered successfully' }); }); const port = process.env.PORT || 3000; app.listen(port, () => console.log(`Server is running on port: ${port}`))
错误信息
POST http://localhost:3000/api/register 404 (Not Found)
已确认服务器运行在http://localhost:3000,服务端已定义/api/register路由,且浏览器能正常连接到服务器,求错误原因及解决办法。
原因及解决方案
1. 端口冲突
Next.js开发服务器默认占用3000端口,若同时启动Next.js和Express,两者会抢占同一端口,导致其中一方未正常启动,无法响应请求。
解决:
- 修改Express端口,比如改为3001:
const port = process.env.PORT || 3001; - 客户端请求地址同步改为
http://localhost:3001/api/register
2. 路由定义顺序错误
若app.post('/api/register')路由定义在404处理中间件或其他拦截路由之后,会导致请求被提前拦截,无法匹配到注册路由。
解决:
- 确保
app.post('/api/register')的定义在app.use(express.json())等通用中间件之后,且在所有全局拦截路由(如404处理)之前。
3. 跨域问题(隐性404)
当Next.js和Express运行在不同端口时,浏览器跨域限制可能会掩盖真实错误,表现为404。
解决:
- 安装cors依赖:
npm install cors - 在Express中启用跨域支持:
const cors = require('cors'); app.use(cors());
4. 服务器未正常启动或路由未加载
检查服务器启动日志,若未输出Server is running on port: 3000或Connected to database,说明服务器启动失败(如数据库连接错误、依赖缺失、模型文件路径错误)。
解决:
- 查看终端报错信息,修复启动问题;
- 确认
User模型文件路径正确,避免因模型加载失败导致服务器异常。
内容的提问来源于stack exchange,提问作者Jolanta
相关产品推荐
相关产品推荐

