后端同时使用@RequestParam和@RequestBody,vue如何传递参数给后端
封装的request请求
service.interceptors.request.use(
config => {
if (store.getters.token) {
config.headers['X-Token'] = getToken()
}
return config
},
error => {
console.log(error) // for debug
return Promise.reject(error)
}
)
service.interceptors.response.use(
response => {
const res = response.data
if (response.status !== 200) {
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000
})
if (res.code === 500) {
// to re-login
MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
confirmButtonText: 'Re-Login',
cancelButtonText: 'Cancel',
type: 'warning'
}).then(() => {
store.dispatch('user/resetToken').then(() => {
location.reload()
})
})
}
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
},
error => {
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
只使用@RequestBody
@PostMapping("/info")
public Object getInfo(@RequestBody String info) {
HashMap map = new HashMap();
map.put("code",20000);
HashMap dataMap = new HashMap();
dataMap.put("getCurrentUserName",ShiroHelper.getCurrentUserName());
dataMap.put("getCurrentStaffName",ShiroHelper.getCurrentStaffName());
dataMap.put("getCurrentStaffType", ShiroHelper.getCurrentStaffType());
dataMap.put("getCurrentUserDefaultRole",ShiroHelper.getCurrentUserDefaultRole());
dataMap.put("getPermissions",getPermissions(ShiroHelper.getCurrentUserName()));
map.put("data",dataMap);
return map;
}
此时vue定义的api请求
export function getInfoApi(data) {
return request({
url: '/info',
method: 'post',
data
})
}
同时使用@RequestBody和@RequestParam的api
@RequestMapping(value = "/users", method = RequestMethod.POST)
public Result<PageInfo<User>> query(@RequestBody(required = false) UserVo userVo,
@RequestParam(required = false, defaultValue = "1") int pageNum,
@RequestParam(required = false, defaultValue = "10") int pageSize) {
PageInfo<User> pageInfo = webUserService.query(userVo, pageNum, pageSize);
return Result.succeed(pageInfo);
}
vue定义的api请求
export function getUserList(data,params) {
const config = {}
config.params = params
config.data = data
return request({
// 使用了config后请求,Content-Type会变成application/x-www-form-urlencoded,此时后端会报错误码415,不支持此格
// 式,所以需要传递headers
headers: {'Content-Type':'application/json;charset=UTF-8'},
url: '/user/users',
method: 'post',
...config
})
}