Vue向后端传数据后端接收为null
由于axios默认发送数据时,数据格式是Request Payload,而并非我们常用的Form Data格式,后端数据就为null,所以在发送之前,需要使用qs模块对其进行处理。
他们的格式
- Request Payload:http://localhost:8080/login?zh=123,pw=123
- Form Data:http://localhost:8080/login,{zh=“123”,pw=“123”}
安装qs
npm install qs
mian.js中添加
import qs from 'qs' //引入qs
Vue.prototype.$qs = qs
vue请求
axios.post('http://localhost:8080/manage/doctor/login.do',this.$qs.stringify({
doctorName:this.form.username,password:this.form.password,// test:3,})
)
.then(response=>{
console.log(response);
})
//获取失败
.catch(error=>{
console.log(error);
alert('网络错误,不能访问');
})
我的后端用的java,给你们看下效果图吧:
Vue捕获后端抛出异常
修改vue项目中 src/utils/request.js中 service.interceptors.response.use内容
设置前
设置后
service.interceptors.response.use(
(response) => {
loadingInstance &&
setTimeout(function () {
loadingInstance.close()
},500)
const res = response.data
return res
},(error) => {
loadingInstance &&
setTimeout(function () {
loadingInstance.close()
},500)
if (error && error.response) {
var { status,data } = error.response
if (status === 401 || status === 403) {
if (!loginInstance && whiteRoutes.indexOf(requestUrl) === -1) {
loginInstance = MessageBox.confirm('登录超时请重新登录','重新登录',{
confirmButtonText: '好的',type: 'warning'
})
.then(() => {
loginInstance = null
store.dispatch('user/resetToken').then(() => {
location.reload()
})
})
.catch(() => {
loginInstance = null
})
}
} else {
if (data) {
Message({
message: data,type: 'error',duration: 5 * 1000
})
} else {
Message({
message: data.message || '服务器异常,请稍后再试或联系管理员',duration: 5 * 1000
})
}
}
} else {
Message({
message: '服务器异常,请稍后再试或联系管理员',duration: 5 * 1000
})
}