vue浏览器跨域问题和vue proxyTable中跨域中pathRewrite配置
vue浏览器跨域问题
当浏览器报如下错误时,则说明请求跨域了。
localhost/:1 Failed to load /test/: 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.
为什么会跨域:
因为浏览器同源策略的限制,不是同源的脚本不能操作其他源下面的对象。
什么是同源策略:
同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。
简单的来说:协议、IP、端口三者都相同,则为同源
解决办法
跨域的解决办法有很多,比如script标签 、jsonp、后端设置cros等等…,但是我这里讲的是webpack配置vue 的 proxyTable解决跨域。
pathRewrite
简单来说,pathRewrite是使用proxy进行代理时,对请求路径进行重定向以匹配到正确的请求地址,
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: ':8083',
changeOrigin: true,
pathRewrite: {
'^/api': '/api' // 这种接口配置出来 :8083/api/login
//'^/api': '/' 这种接口配置出来 :8083/login
}
}
}
},
如何不配置pathRewrite 请求就被转发到 :8083 并把相应uri带上。比如:localhost:8080/api/xxx 会被转发到:8083/api/xxx
- 配置完成后需要重新编译一遍 , 调用接口的时候
// 获取菜单权限
getPermission(){
this.$ajaxget({
url: '/api/getPermission',
data: {},
isLayer: true,
successFc: data => {
console.log(data.data)
}
})
2种数据请求方式: fecth和axios
1、 fetch方式:
在需要请求的页面,只需要这样写(/apis+具体请求参数),如下:
fetch("/apis/test/", {
method: "POST",
headers: {
"Content-type": "application/json",
token: "f4c902c9ae5a2a9d8f84868ad064e706"
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(data => {
console.log(data);
});
2、axios方式:
代码
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/',data).then(res=>{
console.log(res)
})