脚本宝典收集整理的这篇文章主要介绍了vue2.0 proxyTable配置,解决跨域,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
当浏览器报如下错误时,则说明请求跨域了。
localhost/:1 Failed to load http://www.thenewstep.cn/test/testToken.php: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
同源策略
的限制,不是同源的脚本不能操作其他源下面的对象。同源策略
:简单的来说:协议、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:就是需要请求地址的接口域名
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)
})
源码地址: 从这里飞过去
以上是脚本宝典为你收集整理的vue2.0 proxyTable配置,解决跨域全部内容,希望文章能够帮你解决vue2.0 proxyTable配置,解决跨域所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。