在axios文档中:
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
这样后端就没法接收了
如果把data换成params,
在axios文档中:
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
这样后端就没法接收了
如果把data换成params,
import qs from 'qs'
data = qs.stringify(data)
可以放到transformRequest 里去处理,这样就不会影响,你别的代码了
const service = axios.create({
baseURL: baseUrl,
transformRequest: [function (data) {
// data['src'] = 'dev'
if (data instanceof FormData) {
return data
}
data = qs.stringify(data)
return data
}]
})
import axios from 'axios';
let baseUrl = ''
export const htp = axios.create({
baseURL: baseUrl,
timeout: 10000,
headers: {"Content-Type": "application/x-www-form-urlencoded"},//设置头
withCredentials: true//带cookie
});
//拦截处理请求
htp.interceptors.request.use(req => {
return handleRequest(req)
}, error => {
return Promise.reject(error)
})
handleRequest = req => {
let data = req.data
console.log('befor convert', data)
let params = new URLSearchParams();//数据编码
for (let name in data) {
if (data[name] instanceof Date) {
params.append(name, data[name].format("yyyy-MM-dd hh:mm:ss")) //日期对象转换
} else if (data[name] instanceof Object) { //嵌套对象转换,
for (let name2 in data[name]) {
if ('size' == name2) {
params.append('pageSize', data[name][name2])
} else if ('current' == name2) {
params.append('pageNo', data[name][name2])
} else if ('search' == name) {
params.append(`${name2}`, data[name][name2])
} else {
params.append(`${name}.${name2}`, data[name][name2])
}
}
} else {
params.append(name, data[name])//普通属性
}
}
req.data = params.toString()
console.log('after convert', req)
return req
}
6 回答3k 阅读✓ 已解决
6 回答3.5k 阅读✓ 已解决
6 回答2.4k 阅读
5 回答6.4k 阅读✓ 已解决
8 回答3.8k 阅读
2 回答2.7k 阅读✓ 已解决
2 回答2k 阅读✓ 已解决
查阅了资料https://segmentfault.com/p/12...,发现需要后端改接收方式