In the vue project, when the front-end and the back-end perform data requests or submissions, if the back-end does not have cross-domain settings, the front-end will report "No" when debugging the code locally. 'Access-Control-Allow-Origin'header is present on the requestedresource." This kind of cross-domain error.
If you want to debug normally locally, there are three solutions:1. Change header in the background
header('Access-Control-Allow-Origin:*');//允许所有来源访问 header('Access-Control-Allow-Method:POST,GET');//允许访问的方式
jsonp provided byJQuery(Note: jquery is introduced in vue and Baidu is used by yourself)
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(',') } }) } }
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 "/api" directly when requesting data using axios:
getData () { axios.get('/api/bj11x5.json', function (res) { console.log(res) })
Use this method to solve cross-domain problems, and problems may arise if you continue to use this method when packaging and deploying. The solution is as follows:
let serverUrl = '/api/' //本地调试时 // let serverUrl = 'http://f.apiplus.cn/' //打包部署上线时 export default { dataUrl: serverUrl + 'bj11x5.json' }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of the use of ajax and jsonp Detailed explanation of the use of polymorphism in JSThe above is the detailed content of Vue cross-domain normal debugging. For more information, please follow other related articles on the PHP Chinese website!