MERN+Next.js项目POST请求报400 Bad Request却仍成功写入数据库
问题排查与解决步骤
1. 修正跨域配置
服务端部署在Heroku、前端部署在Vercel属于跨域场景,需要在服务端明确配置CORS规则:
- 安装
cors依赖后添加如下配置:
const cors = require('cors'); app.use(cors({ origin: ['你的Vercel正式域名', 'http://localhost:3000'], credentials: true }));
- 前端axios添加全局配置开启凭证携带:
axios.defaults.withCredentials = true;
2. 检查Next.js重写规则
本地开发时生效的接口转发规则在Vercel部署后可能失效,检查next.config.js的rewrites配置需严格按照如下格式编写:
module.exports = { async rewrites() { return [ { source: '/:path*', destination: 'https://你的Heroku接口域名/:path*', }, ] }, }
确保destination字段填写完整的Heroku接口域名,包含https://协议头。
3. 优化服务端错误返回逻辑
原服务端代码catch块仅返回400状态码无错误信息,修改为返回结构化错误信息方便定位问题:
export const createPost = async (req, res) => { const { content, image } = req.body; if(!content.length) { return res.json({ error: 'Content is required' }) } try { const post = new Post({ content, image, postedBy: req.user._id }); await post.save(); const postWithUser = await Post.findById(post._id).populate('postedBy', '-password -secret'); res.json(postWithUser); } catch (e) { console.log('createPost error:', e); // 替换原res.sendStatus(400) res.status(400).json({ error: e.message }) } };
修改后重新部署服务端,查看Heroku日志和前端控制台即可看到具体触发异常,常见部署环境异常包括:MongoDB访问权限不足、populate关联字段不存在、请求体大小超出限制等。
4. 配置axios全局baseURL
未配置重写规则的场景下,相对路径/create-post部署后会默认请求Vercel域名,需给axios配置生产环境baseURL指向Heroku接口:
axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? 'https://你的Heroku接口域名' : 'http://localhost:本地后端端口';
5. 调整请求体大小限制
如果请求包含图片等大体积内容,需要调整express解析中间件的大小限制:
app.use(express.json({ limit: '10mb' })); app.use(express.urlencoded({ extended: true, limit: '10mb' }));
内容的提问来源于stack exchange,提问作者Gavin Fahey
相关产品推荐
相关产品推荐

