前言
vue进行接口调试的时候,如果涉及到服务器和本地的跨域问题的话,用get简单请求是可以获取到数据的,但是如果是post或者带有请求前缀如AccessToken之类的复杂请求的话需要配置config/index.js下的proxytable,否则会报跨域错误。
配置参数
proxyTable: {
// 替换的简写
'/api':{
target:'https://www.apiopen.top', // 接口地址
changeOrigin: true // 是否跨域
pathRewrite:{
'^/api':''//注意实际接口不存在/api就需要重写去除,比较会提示server 503
}
}
},
接口示例
import axios from '../utils/axios';
import qs from 'qs'
const service=axios.create({
baseURL:'/api',//替代接口地址
timeout:5000,
// 处理参数
transformRequest:[function(data){
data=qs.stringify(data);
return data;
}]
})
export default service
export const regist =(key,phone,passwd)=>{
const data={
key,phone,passwd
}
return axios.post('/createUser',data)
}
Vue axios后台post参数为空
根本原因
目前java php node也好,后台接收的post数据都是基于发送时使用的application/x-www-form-urlencoded的传递方式,而axios默认的传递方式为Content-type为application/json,所以导致了默认的post传递数值为空。
解决方案:
1 改写userService(不推荐)
通过URLSearchParams处理参数,URLSearchParams的兼容性并不高,(需要polyfill,支持google不支持ie和360)
// const params=new URLSearchParams({
// key,
// phone,
// passwd
// })
// return axios.post('/createUser',params);
2通过transformRequest每次请求前转换参数
const service=axios.create({
baseURL:'/api',
timeout:5000,
// 处理参数
transformRequest:[function(data){
data=qs.stringify(data);
return data;
}]
})
参考资料:
axios post参数为null解决 https://www.jianshu.com/p/b22d03dfe006
axios发送POST请求时后台接收不到的问题 https://zhuanlan.zhihu.com/p/27498996