Summary of vue's handling of cross domain problems and solutions

  • 2021-11-14 05:06:15
  • OfStack

When you send a network request, the following save message appears. Congratulations on your cross-domain

Access to XMLHttpRequest at 'XXXXX' from origin 'XXXXXX' has been blocked by
CORS policy: Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

1.1 What is cross-domain?

Cross-domain problem appears because of the browser's homology strategy. The so-called homology: two pages have the same protocol (protocol), host (host) and port number (port), which is the core and basic function of the browser. If there is no homology strategy, our browser will be 10 points unsafe and may be attacked at any time.

When the protocol name, domain name and port number are different, cross-domain problems will occur

One point is emphasized here: Cross-domain occurs, not because the request was not sent, but because the request was sent successfully, and the server also returned the data to you, but the browser rejected it for security reasons.

2.2 How to solve cross-domain?

1. Method 1

If conditions permit, you can communicate with the back end. The back end adds a response header when responding, and the front end can handle cross-domain without any operation

2. Method 2

vue scaffolding provides a very simple method:

If you use cli3 or above and there is no configuration file in the directory, you need to create a new vue. config. js file in the root directory to add the configuration information you need


module.exports={
    pages: {
        index: {
        // Entrance 
            entry:"src/main.js",
        },
    },
    devServer: {
        proxy: {
            '/api': {
                target: ' Requested url',
                pathRewrite:{'^/api':''},
                ws: true,
                changeOrigin: true
            }
        }
    }
}

It will create a proxy server to request data from the back end instead of the browser, because there is no cross-domain problem between the server and the server.

The protocol domain name port number of this proxy server is the same as the protocol domain name port number when you run the project. You can request data when

Using http://localhost: 8080/api When you request data, adding/api will recognize that you need to deal with cross-domain. If you don't add/api, you will access the corresponding data in the root directory of the project

3. Method 3

Requests that use jsonp but can only process get, such as post, put, patch, etc., cannot be processed


Related articles: