方法1:后台更改header
header('Access-Control-Allow-Origin:*');//允许所有来源访问
header('Access-Control-Allow-Method:POST,GET');//允许访问的方式
方法2:使用JQury提供的jsonp
//jsop只支持GET请求,利用的是script标签不受同源策略的约束
methods: {
getData () {
$.ajax({
url: 'http://elm-api.caibowen.net/common/getAddress',
type: 'GET',
dataType: 'JSONP',
success: function (res) {
console.log(res);
}
})
}
}
方法3:使用http-proxy-middleware 代理解决(项目使用vue-cli搭建)
例如:请求的url是https://elm-api.caibowen.net/common/getAddress
(1)打开config/index.js,在proxyTable中添写如下代码:
proxyTable: {
'/api': { //使用"/api"来代替"http://f.apiplus.c"
target: 'https://elm-api.caibowen.net', //源地址
changeOrigin: true, //改变源
pathRewrite: {
'^/api': 'https://elm-api.caibowen.net' //路径重写
}
}
}
(2)使用axios请求数据时直接用“/api”
getData () {
axios.get('/api/common/getAddress', function (res) {
console.log(res)
})
//这种方式只能在开发环境中应用
//正式环境中需要用到nginx反向代理