前端Vue向后端发送put请求时,以json数据格式能够执行成功却无法更新数据库数据,单独进行x-www-form-urlencoded格式的接口测试可以成功更新,如何单独对put请求进行请求数据格式更改?
我将axios编写成统一拦截器进行统一管理请求拦截,求Content-Type应该写在什么位置

还是写在put请求的函数参数

前端Vue向后端发送put请求时,以json数据格式能够执行成功却无法更新数据库数据,单独进行x-www-form-urlencoded格式的接口测试可以成功更新,如何单独对put请求进行请求数据格式更改?
我将axios编写成统一拦截器进行统一管理请求拦截,求Content-Type应该写在什么位置


关注让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言问题解答:
import qs from 'qs';
import axios from 'axios';
// 对请求进行transformRequest数据格式化
axios.interceptors.request.use(config => {
if (config.method === 'put') {
// 将请求数据转换为x-www-form-urlencoded格式
config.data = qs.stringify(config.data);
// 添加请求头
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
return config;
});
export default axios;
以上代码将所有的put请求的数据格式均转换为x-www-form-urlencoded格式,可以根据需要对请求头进行修改。 2. Content-Type应该写在什么位置? 对于axios的统一拦截器,建议将Content-Type写在put请求的函数参数中,这样仅对put请求进行更改,不会对其他请求造成影响。 具体代码如下:
import qs from 'qs';
import axios from 'axios';
// 对请求进行transformRequest数据格式化
axios.interceptors.request.use(config => {
if (config.method === 'put') {
// 将请求数据转换为x-www-form-urlencoded格式
config.data = qs.stringify(config.data);
// 添加请求头
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
return config;
});
// put请求
export function putRequest(url, data) {
return axios.put(url, data, {
headers: {
'Content-Type': 'application/json'
}
});
}
以上代码对put请求进行了2次请求头设置,第一次设置为x-www-form-urlencoded格式,第二次设置为json格式。可以根据实际情况进行调整。