After using axios to send the request, I did not get the returned data. I opened the console and found an error as shown in the figure below:
This is a reminder that it is cross-domain. All browsers that use JavaScript support the same-origin policy. The same-origin policy refers to the same domain name/protocol/port number. As long as there is a difference, it will be regarded as a cross-domain request.
The solution is:
1. CORS
The backend resolves cross-domain through CORS, and adds in the response header:
Access-Control-Allow-Origin: <origin>
The front-end can access the back-end API across domains through axios.
2. proxy
Configure proxy proxy cross-domain in vue.config.js:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true
}
}
}
}
In this way, the front-end request '/api' will be proxied to ' http://localhost:8080 ' to achieve cross-domain.
3. JSONP
Get data across domains by dynamically creating <script> tags:
function getdata(url, callback) {
var script = document.createElement('script')
script.src = url + '?callback=' + callback
document.body.appendChild(script)
}
getdata('http://example.com/getdata?a=1', 'callback')
function callback(data) {
console.log(data)
}
The JSON data returned by the server will be used as a parameter of the callback function to achieve cross-domain data acquisition.
4. postMessage
Communicate between two windows across domains:
// window1
window.addEventListener('message', function(e) {
console.log(e.data)
}, false)
// window2
var win = otherWindow.window
win.postMessage('message', 'http://example.com')
Other solutions include Web Sockets, nginx proxy, etc.
To sum up, the methods to solve vue cross-domain are:
1. The backend adds response headers through CORS
2. Vue CLI proxy cross-domain
3. JSONP cross-domain through dynamic <script> tags
4. postMessage cross-window communication
5. Web Sockets
6. nginx reverse proxy
It is very important for front-end engineers to understand the principles and common solutions of cross-domain problems.