When I used the default post method to send data, I found that the backend could not obtain the data. However, I saw in the network that the parameters were indeed passed out. And it is also possible to test with postman. After comparing the two differences, I found that postman uses the form-data format, so I used the form-data format to request again and found that OJBK
Both formats are unusable:
Method 1: Configure transformRequest
Disadvantages: Data in other request formats will also be reformatted (PUT, PATCH)
import axios from "axios" //引入
//设置axios为form-data
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.transformRequest = [function (data) {
let ret = ''
for (let it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
return ret
}]
//然后再修改原型链
Vue.prototype.$axios = axios
There is also this direct quote:
axios({
method: 'post',
url: 'http://localhost:8080/login',
data: {
username: this.loginForm.username,
password: this.loginForm.password
},
transformRequest: [
function (data) {
let ret = ''
for (let it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
ret = ret.substring(0, ret.lastIndexOf('&'));
return ret
}
],
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
Method 2: Add a request interceptor and prescribe the right medicine (recommended)
All major browsers support the encodeURIComponent() function
Add the following code to the encapsulated axios:
//添加请求拦截器
axios.interceptors.request.use(
config => {
//设置axios为form-data 方法2
if (config.method === 'post') {
let data = ''
for (let item in config.data) {
if (config.data[item])
data += encodeURIComponent(item) + '=' + encodeURIComponent(config.data[item]) + '&'
}
config.data = data.slice(0, data.length - 1)
}
return config;
},
error => {
console.log("在request拦截器显示错误:", error.response)
return Promise.reject(error);
}
);
This is the current format