1. 首页
  2. 前端

Vue中用vue-resource POST请求接口时报错Uncaught (in promise)(错误码400)的解决方案

问题描述:

项目中,难免会调用后台接口请求数据,当使用ajax向后端发送POST请求时,会成功调用接口;但是改用vue-resource发送POST请求一直出现400 Bad Request 错误,错误提示Uncaught (in promise),接下来具体分析。

通过Ajax请求数据

用ajax请求时正常,如下:

Vue中用vue-resource POST请求接口时报错Uncaught (in promise)(错误码400)的解决方案

http请求成功详情:

Vue中用vue-resource POST请求接口时报错Uncaught (in promise)(错误码400)的解决方案

通过vue-resource请求数据

使用vue-resource中的post请求时就出现了错误,代码如下:

Vue中用vue-resource POST请求接口时报错Uncaught (in promise)(错误码400)的解决方案

控制台报错Uncaught (in promise),错误码400,如下图:

Vue中用vue-resource POST请求接口时报错Uncaught (in promise)(错误码400)的解决方案

http请求失败详情:

Vue中用vue-resource POST请求接口时报错Uncaught (in promise)(错误码400)的解决方案

可以看出AJAX请求发送200 OK,而vue-resource请求发送400 Bad Request

具体原因可以看出来在请求头中,前者的Content-Type=application/x-www-form-urlencoded,导致请求体中的数据格式为Form Dataid=1;而后者的Content-Type=application/json,导致请求体中的数据格式为Request PayLoad: { id:1 }。显然服务端接收第一种参数格式而拒绝第二种,所以抛出400状态码。

所以要做的就是将vue-resource请求体中的参数格式指定为Form Data即可。

emulateJSON
boolean类型 默认值为false
用途:将request body以application/x-www-form-urlencoded content-Type发送

在发送POST请求的options选项中添加 {emulateJSON:true} 即可。正确的http请求如下:

Vue中用vue-resource POST请求接口时报错Uncaught (in promise)(错误码400)的解决方案

http请求成功详情:

Vue中用vue-resource POST请求接口时报错Uncaught (in promise)(错误码400)的解决方案

总结

请求头中的Content-Type字段会说明实体主体内对象的媒体类型。AJAX默认的Content-Type=application/x-www-form-urlencoded;vue-resource的POST请求默认的Contnet-Type=application/json;通过指定emulateJSON的值来指定vue-resource Content-Type的值。

原创文章,作者:Ferrycoln,如若转载,请注明出处:https://ms200.cn/archives/370

发表评论

邮箱地址不会被公开。 必填项已用*标注

联系我们

在线咨询:点击这里给我发消息

邮件:499661635@qq.com.com

工作时间:周一至周五,9:30-18:30

QR code