之前发请求时经常出现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的类型
而我这次其实并没有用到,但是我之前试错的时候用到了,涉及到格式就一起放在一起,已经注释掉了