Below I will share with you an article about the ajax cross-domain solution when developing vue-cli. It has a good reference value and I hope it will be helpful to everyone.
Purpose: When developing a project built using vue-cli, if you want to access the background interface to obtain data, cross-domain problems will occur.
Configure the following in config/index.js
[That is, when making an ajax request, any address starting with /api The request address is parsed into the target address, and the target is the backend interface address you want]
proxyTable: { ‘/api': { target: ‘https://188.188.18.8‘, changeOrigin: true, pathRewrite: { ‘^/api': ” } } } “`
vue-resource call example
this.$http.get('/api/v4/user/login', [options]).then(function(response){ // 响应成功回调 }, function(response){ // 响应错误回调 });
axios call example
axios({ method: 'get', headers: {'Accept': '*/*'}, url: '/api/v4/user/login', data: options }) .then(function (response) { console.log(response.data) }) .catch(function (error) { console.log(error) })
Explanation of the principle:
In the configuration: target: 'https://188.188.18.8'
In the vue-resource example above, the first parameter is: /api/v4/user/login
will be automatically parsed by the local server as https://188.188.18.8/v4/user/login And this is the official address we need.
Cross-domain principle (local files pretend to be on the remote server):
Open the page through the browser, when a request is made: the address of the local server (usually localhost:8080 or 127.0.0.1 :8080) will receive this request, and then find that the request address contains the string /api, then the local server will change the request address to https://188.188.18.8/v4/ (configuration address) user/login (call The detailed address of the method).
At the same time, the address of the local server will change from localhost:8080 to https://188.188.18.8/v4/. The result is:
Our local files will be considered to be placed at the target address. (https://188.188.18.8/v4/) On the server, if the file on the current server requests something else from the server, it is naturally not cross-domain.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
ImplementationajaxDrag and drop upload files (with code)
Achieved through Ajax Method of dynamically loading line charts (graphic tutorial)
jquery ajaxImplementing file upload function (with code)
The above is the detailed content of When developing vue-cli, solutions to cross-domain ajax (strongly recommended). For more information, please follow other related articles on the PHP Chinese website!