最近在改造一个旧系统的时候,前端换成了vue+axios,遇到一个坑,axios发送的请求,Spring MVC的controller里面获取参数失败.
经过查看官方文档后,解决了问题,记录一下:
前端代码(axios):
fetchJobs: function() {
//这种赋值操作不可少!
var _this = this;
/*原因:
在请求执行成功后执行回调函数中的内容,
回调函数处于其它函数的内部this不会与任何对象绑定,为undefined
*/
var startIndex = (_this.currentPage - 1) * this.pageSize;
//参数必须这样组装一下 要不然传入的是一个map
const params = new URLSearchParams();
params.append("start", startIndex);
params.append("limit", _this.pageSize);
instance
.post("/job/list", params)
.then(function(response) {
_this.jobList = response.data.result;
_this.totalCount = response.data.totalCount;
console.log(_this.jobList);
})
.catch(function(error) {
console.log(error);
});
}
前端代码(vue-resource):
this.$http.post('http://localhost:8080/job/list', {
start: startIndex,
limit: this.pageSize
},
{
//这句是关键 不可缺少
emulateJSON: true
}
)
.then(function (response) {
this.jobList = response.data.result;
this.totalCount = response.data.totalCount;
console.log(this.jobList);
})
.catch(function (error) {
console.log(error);
});
}
后端代码:
String pageNo =request.getParameter("start");
String pageSize =request.getParameter("limit");
logger.info("参数获取===============>pageNo:" +pageNo);
logger.info("参数获取===============>pageSize:" +pageSize);