I. What is cross-domain?
-
Because of the browser’s same-origin policy (protocol, domain name, port any difference), accessing non-same-origin data requires cross-domain processing. If non-same-origin — there are three behaviors that are restricted:
- Cookie,LocalStorage cannot read
- DOM and JS objects are not available
- Invalid AJAX request (can be sent, but browser will reject the response)
What are the ways to achieve cross-domain?
- JSONP
- CORS(done on the server side, header information can be set)
- Cross-domain requests using reverse proxy servers (server-side Nginx/Apache)
3. The json
-
Implementation principle:
- Create a script tag dynamically
- Place the address of the target data in the SRC attribute of the script tag, and concatenate the callback argument with the callback function name in the request address
- Defines a callback function that is called when a data request succeeds
-
Jq-wrapped Ajax methods for cross-domain requests:
<script> $.ajax({ type: 'GET', url: 'http://localhost:4000/jsonp? callback=? ', / /? This can be interpreted as the success method below. success:function(data) {// data is the data returned by the server console.log(data); }, dataType:'jsonp'// dataType must be jsonp}); </script>Copy the code
Four CORS.
-
Cross Origin Resource Share (backend)
- In the request header when the server responds to the client
Access-Control-Allow-Origin", "*"
// Set cors app.all(The '*'.function (req, res, next) { res.header("Access-Control-Allow-Origin"."*"); res.header('Access-Control-Allow-Methods'.'PUT, GET, POST, DELETE, OPTIONS'); res.header('Access-Control-Allow-Headers'.'Content-Type'.'mytoken'); next(); }); Copy the code
- In the request header when the server responds to the client