当浏览器报如下错误时,则说明请求跨域了。

同源策略
的限制,不是同源的脚本不能操作其他源下面的对象。同源策略
:简单的来说:协议、IP、端口三者都相同,则为同源
跨域的解决办法有很多,比如script标签
、jsonp
、后端设置cros
等等...,但是我这里讲的是webpack配置vue 的 proxyTable
解决跨域。
这里我请求的地址是 http://www.thenewstep.cn/test/testToken.php
那么在ProxyTable中具体配置如下:
proxyTable: {
‘/apis‘: {
// 测试环境
target: ‘http://www.thenewstep.cn/‘, // 接口域名
changeOrigin: true, //是否跨域
pathRewrite: {
‘^/apis‘: ‘‘ //需要rewrite重写的,
}
}
target:就是需要请求地址的接口域名
配置完必须要重启node服务(重新npm run dev)才会生效!!!
fecth和axios
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);
});
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"
axios请求页面代码
this.$axios.post(‘/apis/test/testToken.php‘,data).then(res=>{
console.log(res)
})
参考来源:https://segmentfault.com/a/1190000014396546
原文:https://www.cnblogs.com/meijifu/p/13278373.html