When encountering an interface that needs to use a put request in the project, the method used is x-www-form-urlencoded
Sorting out the steps—the request.js file of the project is configured with the json method by default
import axios from "axios"
axios.interceptors.request.use(function (config) {
console.log(config)
// 请求头配置带token
const token = sessionStorage.getItem('token_kpi')
if(token) {
config.headers.Authorization = token
}
return config
}, function(error) {
return Promise.reject(error)
})
The console print results are as follows
You can see that the Content-Type in the headers is null
Problem-solving idea-1: When a put request is initiated, the value of Content-Type in headers needs to be changed to application/x-www-form-urlencoded
request.js add code
axios.interceptors.request.use(function (config) {
const token = sessionStorage.getItem('token_kpi')
if(token) {
config.headers.Authorization = token
}
if(config.method === 'put') {
// 判断如果是put请求, 配置content-type
config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
}else {
config.headers['Content-Type'] = 'application/json'
}
console.log(config)
return config
}, function(error) {
return Promise.reject(error)
})
Here conifg.method is used to judge the put request at that time,
and the Content-Type in config.headers is assigned 'application/x-www-form-urlencoded'
At this time, config is printed to the console and can be found
The value of Content-Type in headers becomes application/x-www-form-urlencoded
and other interface request types are not affected
Problem-solving idea-2: Directly modify the encapsulated interface api.js file
// 修改密码
export function changePassword(data) {
return request({
url: 'xxx/member/updatePwd',
headers: {
// 修改请求头
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'put',
data
})
}
This article focuses on learning records