A way to send ajax requests
- XHR (XMLHttpRequest) : xhr.open(), xhr.send()
- JQuery: XHR encapsulation, small size, support request and response interceptors
- Axios: Encapsulates XHR, vUE official recommendation
- Fetch: Level with XHR, but not compatible with IE
Two. Causes of cross-domain
If a protocol, subdomain name, main domain name, or port number is different, the domain name is counted as different. Requests for resources between different domains are considered cross-domain.
3. Misunderstanding of cross-domain
When the browser makes a request to the server, even if there is a cross-domain problem, the server will still respond to the request and return the data to the browser. However, when the browser finds that there is a cross-domain problem after getting the data, the browser will not give the data to the page, which is equivalent to withholding the data (as shown in the following figure).
This is not to say that cross-domain requests don’t go out at all, or that the server doesn’t respond to requests at all, which is the wrong idea (as I thought before).
4. Cross-domain solutions
- Cors: Server-side configuration, no front-end configuration (cross-domain solution in a real sense)
- Jsonp: The SRC attribute of the Script tag is not restricted by the same origin policy, but it can only solve GET requests
- Proxy server: the same as the front-end page, the data returned by him does not exist cross-domain problems, as shown in the figure.
(Note: The proxy server and server are non-same-origin, but there is no cross-domain problem because HTTP requests are used between servers, not Ajax technology)
5. Configuring a proxy server
- Nginx (relatively cumbersome and requires some back-end knowledge)
- Proxy :(relatively simple, familiar with a certain webpack configuration)
Configuring a single agent:
/ / the vue. Config. Js/webpack config. Js / / advantages: simple configuration / / disadvantages: Module. Exports ={deServer:{proxy:'http://xxx.xxx.xxx:5000'}}Copy the code
Configuring multiple agents:
/ / the vue. Config. Js/webpack config. Js / / advantages: you can configure multiple agents, and is a flexible control request agent / / disadvantages: Cumbersome configuration, Module. exports={deServer:{proxy:{'/ API01 ':{target:'http://xxx.xxx.xxx:5000', changeOrigin:true, // Override the request, according to the interface details, PathRewrite :{'^/ API01 ':'}}, '/ API02 ':{target:'http://xxx.xxx.xxx:5001', changeOrigin:true, Check whether pathRewrite:{'^/ API02 ':'}}}}} // When changeOrigin is set to true, the host of the request header received by the server is the same as the server address. The host of the request header received by the server is the same as the front-end addressCopy the code