In the vue project, when the front-end and back-end perform data requests or submissions, if the back-end does not set cross-domain settings, the front-end will report "No 'Access-Control-Allow-Origin' header is present on the" when debugging the code locally. requested resource." This cross-domain error.
If you want to debug normally locally, there are three solutions:
1. Change the header in the background
header('Access-Control-Allow-Origin:*');//允许所有来源访问 header('Access-Control-Allow-Method:POST,GET');//允许访问的方式
This way you can request data across domains.
2. Use jsonp provided by JQuery (Note: jquery is introduced in vue and Baidu is used by Baidu)
##
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(',') } }) } }
proxyTable: { '/api': { //使用"/api"来代替"http://f.apiplus.c" target: 'http://f.apiplus.cn', //源地址 changeOrigin: true, //改变源 pathRewrite: { '^/api': 'http://f.apiplus.cn' //路径重写 } } }
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' }
The above is the detailed content of Vue cross-domain solution. For more information, please follow other related articles on the PHP Chinese website!