This is the 13th day of my participation in the August More Text Challenge
What is cross-domain?
Instead of introducing what cross-domain is, let’s introduce the pre-knowledge of cross-domain (same-origin policy). The same origin policy is an important security policy for browsers. The same origin policy means that the browser will only allow scripts on the first page to access data on the second page if both pages have the same source. In this case, the protocol, domain name, and port number are of the same origin.
Are cross-domain requests sent to the server?
The cross-domain request was actually sent to the server, and the client received the returned message. However, the browser received the message and found that the message violated the same origin policy and was not allowed to cross domains, so it reported an error when parsing the message.
What is and isn’t restricted by the same Origin policy?
Restrict the following:
- Ajax requests.
- Cookies, LoaclStorage.
- The DOM object.
The following content is not restricted:
Cross-domain solutions
Scheme 1: JSONP
Core idea: use the SCRIPT tag in HTML is not restricted by the same origin policy to carry out cross-domain, in the client script to define a good processing function, and then pass the request parameters to the server, the server after string splicing back to call the function.
- The client
- Server side (Express)
CodeSandBox online demo
The advantages and disadvantages
- Advantages: Simple and convenient.
- Disadvantages: Only get method is supported and server side collaboration is required.
Plan 2: CORS
CORS (Cross-domain Resource Sharing) uses HTTP headers to tell the browser which clients from different sources can access resources on the site. The key to realizing cross-domain CORS is on the server. You can enable CORS on the server as long as access-Control-allow-Origin is set on the server. This attribute can set which domain names can Access the server. CORS will divide the request into simple request and precheck request when cross-domain. Simple request.
1. Simple request (can be sent directly)
The request methods are of the following types:
- GET
- POST
- HEAD
2. Pre-check request
A precheck request must first send a preliminary precheck request to the server for permission before it can proceed with the main request. The following describes the requests that need to be prechecked.
- The request is not for a GET/HEAD/POST method.
- Request POST method and content-type is not text/plain, Application/X-www-form-urlencoded or multipart/form-data.
- The request has a custom header set, such as X-Pingother.
CORS cross-domain instances
- The client
- The server side