vue2.0 proxyTable配置,解决跨域
跨域的解决办法有很多,比如script标签 、jsonp、后端设置cros等等…,但是我这里讲的是webpack配置vue 的 proxyTable解决跨域。
这里我请求的地址是 http://kaizhong.a-ziqin.club/api/index/ceshi
那么在ProxyTable中具体配置如下:
proxyTable: {
'/apis': {
// 测试环境
target: 'http://www.thenewstep.cn/', // 接口域名
changeOrigin: true, //是否跨域
pathRewrite: {
'^/apis': '' //需要rewrite重写的,
}
}
},
proxyTable: {
'/apis': {
// 测试环境
target: 'http://www.thenewstep.cn/', // 接口域名
changeOrigin: true, //是否跨域
pathRewrite: {
'^/apis': '' //需要rewrite重写的,
}
}
},
proxyTable: { '/apis': { // 测试环境 target: 'http://www.thenewstep.cn/', // 接口域名 changeOrigin: true, //是否跨域 pathRewrite: { '^/apis': '' //需要rewrite重写的, } } },
target:就是需要请求地址的接口域名
这里列举了2种数据请求方式: fecth和axios
1、 fetch方式:
在需要请求的页面,只需要这样写(/apis+具体请求参数),如下:
fetch("/apis/test/testToken.php", {
method: "POST",
headers: {
"Content-type": "application/json",
token: "f4c902c9ae5a2a9d8f84868ad064e706"
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => {
console.log(data);
});
fetch("/apis/test/testToken.php", {
method: "POST",
headers: {
"Content-type": "application/json",
token: "f4c902c9ae5a2a9d8f84868ad064e706"
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => {
console.log(data);
});
fetch("/apis/test/testToken.php", { method: "POST", headers: { "Content-type": "application/json", token: "f4c902c9ae5a2a9d8f84868ad064e706" }, body: JSON.stringify(data) }) .then(res => res.json()) .then(data => { console.log(data); });
2、axios方式:
main.js代码
import Vue from 'vue'
import App from './App'
import axios from 'axios'
Vue.config.productionTip = false
Vue.prototype.$axios = axios //将axios挂载在Vue实例原型上
// 设置axios请求的token
axios.defaults.headers.common['token'] = 'f4c902c9ae5a2a9d8f84868ad064e706'
//设置请求头
axios.defaults.headers.post["Content-type"] = "application/json"
import Vue from 'vue'
import App from './App'
import axios from 'axios'
Vue.config.productionTip = false
Vue.prototype.$axios = axios //将axios挂载在Vue实例原型上
// 设置axios请求的token
axios.defaults.headers.common['token'] = 'f4c902c9ae5a2a9d8f84868ad064e706'
//设置请求头
axios.defaults.headers.post["Content-type"] = "application/json"
import Vue from 'vue' import App from './App' import axios from 'axios' Vue.config.productionTip = false Vue.prototype.$axios = axios //将axios挂载在Vue实例原型上 // 设置axios请求的token axios.defaults.headers.common['token'] = 'f4c902c9ae5a2a9d8f84868ad064e706' //设置请求头 axios.defaults.headers.post["Content-type"] = "application/json"
axios请求页面代码
methods: {
onLoad(){
let data={}
this.$axios.get('/apis/api/index/ceshi',data).then(res=>{
console.log(res)
})
}
},
methods: {
onLoad(){
let data={}
this.$axios.get('/apis/api/index/ceshi',data).then(res=>{
console.log(res)
})
}
},
methods: { onLoad(){ let data={} this.$axios.get('/apis/api/index/ceshi',data).then(res=>{ console.log(res) }) } },