首先参考一位网上好友的文章 :blog.csdn.net/yunfeng482/…
当出现如下问题的时候
当浏览器报如下错误时,则说明请求跨域了。
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.
为什么会跨域: 因为浏览器同源策略的限制,不是同源的脚本不能操作其他源下面的对象。
什么是同源策略: 同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。 简单的来说:协议、IP、端口三者都相同,则为同源
解决办法 跨域的解决办法有很多,比如script标签 、jsonp、后端设置cros等等…,但是我这里讲的是webpack配置vue 的 proxyTable解决跨域。
pathRewrite 简单来说,pathRewrite是使用proxy进行代理时,对请求路径进行重定向以匹配到正确的请求地址,
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://XX.XX.XX.XX:8083',
changeOrigin: true,
pathRewrite: {
'^/api': '/api' // 这种接口配置出来 http://XX.XX.XX.XX:8083/api/login
//'^/api': '/' 这种接口配置出来 http://XX.XX.XX.XX:8083/login
}
}
}
},
如何不配置pathRewrite 请求就被转发到 XX.XX.XX.XX:8083 并把相应uri带上。比如:localhost:8080/api/xxx 会被转发到XX.XX.XX.XX: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/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"
axios请求页面代码
this.$axios.post('/apis/test/testToken.php',data).then(res=>{
console.log(res)
})
原文链接:blog.csdn.net/yunfeng482/…
问:proxyTable 里面的pathRewrite里面的‘^/iclient’:'' 什么意思?
答:用代理, 首先你得有一个标识, 告诉他你这个连接要用代理. 不然的话, 可能你的 html, css, js这些静态资源都跑去代理. 所以我们只要接口用代理, 静态文件用本地.
'/iclient': {}
, 就是告诉node
, 我接口只要是'/iclient'
开头的才用代理.所以你的接口就要这么写 /iclient/xx/xx
. 最后代理的路径就是 http://xxx.xx.com/iclient/xx/xx
.
可是不对啊, 我正确的接口路径里面没有/iclient
啊. 所以就需要 pathRewrite
,用''^/iclient'':''
, 把'/iclient'
去掉, 这样既能有正确标识, 又能在请求接口的时候去掉iclient
.
proxyTable: {
'/api':{
target:'http://localhost:8083',
// secure:true,
changeOrigin:true,
pathRewrite:{
"^/api":""
}
}
}
1.要理解pathRewrite,首先要明白proxyTable下‘/api’的作用。
使用代理, 首先需要有一个标识, 标明哪些连接需要使用代理,只有有标识的连接才用代理。”/api”就是告知,接口以”/api”开头的才用代理,所以写请求接口时要使用“/api/xx/xx” (浏览器地址栏展示)的形式,使用代理后生成的请求路径就是’http://localhost:8083/api/xx/xx’(这个就是真实的后台请求地址)
2.pathRewrite中 “^/api”:""的作用
当实际需要请求的路径里面没有”/api“时. 就需要 pathRewrite,用’’^/api’’:’’, 把’/api’去掉, 这样既能有正确标识, 又能在请求到正确的路径。