Home >Web Front-end >H5 Tutorial >Vue cross-domain solution
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(',') } }) } }This method can also solve cross-domain problems question. 3. Use http-proxy-middleware proxy solution (the project is built using vue-cli scaffolding) For example, the requested url: "http://f.apiplus.cn/bj11x5.json "1. Open config/index.js and add the following code in proxyTable:
proxyTable: { '/api': { //使用"/api"来代替"http://f.apiplus.c" target: 'http://f.apiplus.cn', //源地址 changeOrigin: true, //改变源 pathRewrite: { '^/api': 'http://f.apiplus.cn' //路径重写 } } }2. Use it directly when requesting data using axios" /api”:
getData () { axios.get('/api/bj11x5.json', function (res) { console.log(res) })Use this method to solve cross-domain problems. If you still use this method when packaging and deploying, problems will arise. The solution is as follows:
let serverUrl = '/api/' //本地调试时 // let serverUrl = 'http://f.apiplus.cn/' //打包部署上线时 export default { dataUrl: serverUrl + 'bj11x5.json' }Define a serverUrl to replace our "/api" during debugging. When packaging, you only need to replace "http://www.xxx. com" to replace this "/api".
The above is the detailed content of Vue cross-domain solution. For more information, please follow other related articles on the PHP Chinese website!