Nest POST请求Swagger正常但Axios调用报500错误求助
Nest POST请求Swagger正常但Axios调用报错问题
Nest后端的/activity/createActivity接口在Swagger中调用正常,但用Axios发起POST请求时出现异常:预检请求返回204 No Content,实际XHR请求返回500错误,后端抛出SQLite非空约束错误。
可正常运行的Swagger请求(curl)
curl -X 'POST' \ 'http://localhost:3000/activity/createActivity' \ -H 'accept: */*' \ -H 'Content-Type: application/json' \ -d '{ "name": "any string", "imagePath": "https://www.image.com/image.png", "description": "any string", "category": 0 }'
本人的Axios代码
接口调用方法
async addActivity(): Promise<Activity> { const activity = await http.post<Activity>("/activity/createActivity", { name: "x", imagePath: "x", description: "x", category: 0, }); return activity.data; }
Axios实例配置
import axios from "axios"; export default axios.create({ baseURL: "http://localhost:3000", headers: { "Content-type": "application/json" }, });
后端返回错误
SQLITE_CONSTRAINT: NOT NULL constraint failed: activities.name
QueryFailedError: SQLITE_CONSTRAINT: NOT NULL constraint failed:
activities.name
at Statement.handler (C:\Users\PC0\WebstormProjects\sprogstimulering-backend\src\driver\sqlite\SqliteQueryRunner.ts:113:26)
已排查内容
- 后端已开启CORS,其他请求正常运行
- 尝试用
body包裹请求参数,无效果 - 未启用授权,排除权限问题
- 发现请求头
Content-Type为"application/x-www-form-urlencoded, application/json",响应头为"Content-Type: application/json; charset=utf-8"
问题分析与解决方案
核心原因
请求头中同时存在application/x-www-form-urlencoded和application/json两种Content-Type,导致Nest无法正确解析JSON格式的请求体,最终数据库接收到的name字段为null,触发非空约束错误。
解决步骤
- 排查请求头覆盖问题:检查是否存在全局Axios拦截器或其他代码修改了请求头,导致Content-Type被追加或替换。
- 手动指定请求头:在POST请求中显式设置Content-Type,确保优先级高于实例配置:
async addActivity(): Promise<Activity> { const activity = await http.post<Activity>("/activity/createActivity", { name: "x", imagePath: "x", description: "x", category: 0, }, { headers: { "Content-Type": "application/json" } }); return activity.data; }
- 验证请求体解析:在Nest控制器中添加日志,打印接收到的请求体,确认参数是否正确传递:
@Post('createActivity') async create(@Body() createActivityDto: CreateActivityDto) { console.log('Received body:', createActivityDto); return this.activityService.create(createActivityDto); }
- 检查Axios实例完整性:确认是否有其他代码修改了导出的Axios实例,比如全局拦截器错误地修改了headers。
内容的提问来源于stack exchange,提问作者Wojciech Wirowski
相关产品推荐
相关产品推荐

