Cross-origin vue Solution
Vue cross-origin Solution
In a vue project, if cross-origin is not set in the background when a data request or submission is made between the frontend and backend, the front-end will report "No 'access-Control-Allow-origin' header is present on the requested resource. "Cross-origin error.
There are three solutions to normal local debugging:
1. Change the header in the background
Header ('access-Control-Allow-Origin: * '); // Allow all sources to Access the header ('access-Control-Allow-Method: POST, get '); // allowed access method
In this way, you can request data across domains.
Ii. Use jsonp provided by JQuery (Note: jquery is introduced in vue, 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 the cross-origin problem.
3. Use http-proxy-middleware proxy (the project is built using vue-cli scaffolding)
For example, the request url is "http://f.apiplus.cn/bj11x5.json"
1. Open config/index. js and add the following code in proxyTable:
ProxyTable: {'/api': {// use "/api" to replace "http://f.apiplus.c" target: 'http: // f.apiplus.cn ', // source address changeOrigin: true, // change source pathRewrite: {'^/api': 'http: // f.apiplus.cn '// rewrite path }}}
2. directly use "/api" when requesting data using axios ":
getData () { axios.get('/api/bj11x5.json', function (res) { console.log(res) })
Cross-origin is solved through this method, and problems may occur during packaging and deployment. The solution is as follows:
Let serverUrl = '/api/' // local debugging // let serverUrl = 'HTTP: // f.apiplus.cn/'// export default {dataUrl: serverUrl + 'bj11x5. json '}
When debugging, define a serverUrl to replace our "/api", and at the end of packaging, just replace "http://www.xxx.com" with this "/api.