之前发请求时经常出现400的错误,一开始以为是前后端的类型不同,后来经过传送一个Object对象发现自己请求的格式不对,更改了请求头也莫名其妙的传送过去了
通常格式
const axios = require('axios')
axios.post(url,data,other)
每一部分之间需要用逗号隔开,每一部分用{}将他们包裹起来,other表示其他需要更改的信息
比如更改请求头中Content-Type的信息,例子如下:后端是设置了一个Route类
public class Route {
@TableId(type = IdType.AUTO)
private int routeId;
private String routeTitle;
private String routePath;
private String routeComment;
private String routePic;
private String routeLocation;
private String createTime;
private int createUser;
}
Controller层
@RequestMapping("/map")
@RestController
public class RouteController {
@Autowired
private RouteService routeService;
@PostMapping("/route")
public int insertPoints(@RequestBody Route route){
return routeService.insertPoints(route);
}
}
前端关键代码:
const axios = require('axios')
axios.post('/map/route',
{
routePath: this.route.routePath,
routeLocation: this.route.routeLocation,
routeTitle: this.route.routeTitle,
createUser: this.route.createUser,
routeComment: this.route.routeComment
}
//, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
)
.then(res => {
if (res.data == 1) alert('添加成功')
}).catch(res => {
alert('添加失败')
})
如果前端使用Formdata()对象就需要修改headers中的Content-Type的类型
而我这次其实并没有用到,但是我之前试错的时候用到了,涉及到格式就一起放在一起,已经注释掉了
本文详细介绍了在前后端交互过程中遇到的HTTP 400错误,探讨了错误产生的原因,主要是请求格式不正确。通过示例展示了如何使用axios库进行POST请求,并调整Content-Type来解决问题。同时,解释了使用FormData的情况以及如何处理相关头部信息。
6664

被折叠的 条评论
为什么被折叠?



