How to solve cross-domain problems in front-end common problems?

1. Reasons for cross-domain

When the browser sends a request, the requested address is not exactly the same as the browser’s protocol domain name port . In order to protect your security, the browser will report an error message

Note: Not all cross-domain requests will report errors. For example, ordinary css requests and image requests will not report
errors. Two conditions must be met for errors in cross-domain requests:

1. The browser's same-origin policy

2. The request type is ajax type

Two, the solution

Actual best solution: Write code in the backend (CORS) to add the necessary response headers in the response, so that the browser does not report an error after the response comes back.
The following is a temporary expedient:

1. The front end uses JSONP to send requests (jsonp is not an ajax request)

2. Server proxy (webpack proxy)

3. How to use vue-cli to set proxy forwarding

Step1: Add the following configuration in vue.config.js:

module.exports = {   devServer: {     // Proxy configuration     proxy: {         // If the request address starts with /api, the proxy mechanism will be triggered         // http://localhost:9588/api/login -> http:// line Address on /api/login '         /api': {           target: 'http://the real interface address we want to proxy'          }       }     } }   }











step2: Delete the base address

const request = axios.create({

  baseURL: '',

  timeout: 5000

})

 step3: After modifying the configuration file, restart the project to see the effect 

Notice:

1. If the backend has already done cross-domain processing, the frontend does not need to do it again

2. Proxy forwarding can only be used in the development stage, and it cannot be used if it no longer enjoys the service of webpack server after going online

principle:

1. When the vue-cli scaffolding tool is started, it will open a server of the front-end project, and users in the same LAN can access it through the ip address.
2. The vue-cli scaffolding supports configuring a proxy: forward the specified type of request to the target server.

  2.1 Since the protocol domain name and port
are   unified between the proxy service and the front-end service , there is no cross-domain problem, and the request can be sent directly. send request

In this way, we can forward the interface through the server proxy to solve cross-domain problems in the development environment, because vue-cli has built this technology for us, so we only need to simply configure it according to the above steps.

The following is a graphical understanding:

Guess you like

Origin blog.csdn.net/weixin_48082900/article/details/128424872