方法1.后台更改header
header('Access-Control-Allow-Origin:*');//允許所有來源訪問
header('Access-Control-Allow-Method:POST,GET');//允許訪問的方式
方法2.使用JQuery提供的jsonp
methods: {
getData () {
var self = this
$.ajax({
url: 'http://f.apiplus.cn/bj11x5.json',
type: 'GET',
dataType: 'JSONP',
success: function (res) {
self.data = res.data.slice(0, 3)
self.opencode = res.data[0].opencode.split(',')
}
})
}
}
方法3.使用http-proxy-middleware 代理解決(項目使用vue-cli腳手架搭建)
例如請求的url:“http://f.apiplus.cn/bj11x5.json”
1、打開config/index.js,在proxyTable中添寫如下代碼:
proxyTable: {
'/api': { //使用"/api"來代替"http://f.apiplus.c"
target: 'http://f.apiplus.cn', //源地址
changeOrigin: true, //改變源
pathRewrite: {
'^/api': 'http://f.apiplus.cn' //路徑重寫
}
}
}
2、使用axios請求數據時直接使用“/api”:
getData () {
axios.get('/api/bj11x5.json', function (res) {
console.log(res)
})
通過這中方法去解決跨域,打包部署時還按這種方法會出問題。解決方法如下:
let serverUrl = '/api/' //本地調試時
// let serverUrl = 'http://f.apiplus.cn/' //打包部署上線時
export default {
dataUrl: serverUrl + 'bj11x5.json'
}
附:
方法二引入jq
1.下載依賴
cnpm install jquery --save-dev
2.在webpack.base.conf.js文件中加入
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
],
3.在需要的temple里引入也可以在main.js里全局引入
import $ from 'jquery'
eg:
<template> <div class="source"> source{{data}} </div> </template> <script> import $ from 'jquery' export default({ name:"source", data(){ return{ data:"" } }, created(){ this.getData() }, methods:{ getData () { var self = this $.ajax({ url: '你要請求的url', type: 'GET', dataType: 'JSONP', success: function (res) { self.data = res.result } }) } } }) </script> <style> </style>