vue浏览器跨域问题及解决办法
当浏览器报如下错误时,说明请求跨域。
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.
跨域的原因:
因为浏览器的同源策略的限制,不是同源的脚本不能操作其他源下面的对象。
什么是同源策略:
同源策略是一种约定,它是浏览器最核心也是最基本的安全功能,如果少了同源策略,则浏览器的正常功能可能会受到影响。可以说web是构建在同源策略基础上的,浏览器只是针对同源策略的一种实现,简单来说:协议、IP、端口三者相同,则为同源。
解决办法:
跨域的解决办法有很多,比如script标签、jsonp、后端设置cros等等。但是在webpack配置vue的proxyTable解决跨域。
在ProxyTable 中具体配置:
ProxyTable:{
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://www.baidu.com/',//接口域名
changeOrigin: true,//是否跨域
pathRewrite:{
'^api':'' //需要rewrite重写的
}
}
}
}
请求的两种方式:
fecth和axios
1·fecth方式:
在需要请求的页面,只需要这样写(/api/+具体请求的参数):
fecth("/api/test/teskToken.php",{
method: "POST",
headers:{
"Content-type":"application/json",
token:"3333333333333333333333"
},
body: JSON.stringfy(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实例原型上
//设置token
axios.defaults.headers.common['token'] = '3333333333333333'
//设置请求头
axios.defaults.headers.post['Content-type'] = 'application/json'
在请求数据页面:
this.$axios.post('/api/test/testpai',data).then(res =>{
console.log(res)
}).catch(err =>{
console.log(err)
})