比如你用vue-resource的get方法请求 https://news-at.zhihu.com/api/4/version/android/2.3.0
这个接口,会报‘Access-Control-Allow_Origin’ header。。。。错误。意思就是,人家服务端不接受你访问。
node.js的解决方案是,在工程的config文件夹下面,将index.js里面的代码,改为如下
proxyTable: {
'/api': {
target:'https://news-at.zhihu.com/api',
changeOrigin:true,
pathRewrite: {
'^/api':''
}
}
},
在main.js里面加入
Vue.prototype.HOST='/api'
然后就可以使用get方式请求了
this.$http.get('/api/4/version/android/2.3.0',{},{
}).then(function(res) {
this.$message(res.data.msg)
},function(error) {
console.log(error)
})
出现这种情况只有两种解决方案
1.在服务端加上
//解决浏览器请求的跨域问题
response.setHeader("Access-Control-Allow-Origin","*");
2 前端做代理,上面的node.js解决方案就是代理思路。
参考了如下资料