Cross domain – Error cause and solution

What causes the browser to report a cross-domain error

Cross-domain error: Ajax requests from different sources

When a browser makes an HTTP request to a Web server, a cross-domain problem occurs if the following three conditions are met, causing the Ajax request to fail:

(1) Different urls for both sides of the request and response.

Two-way URL: The URL of the page from which the request is made and the requested resource

The same protocol, same domain name, and same port are the same.

Here are the different sources:

Request from http://127.0.0.1:5500/message_front/index.html http://localhost:8080/getmsg

There are many requests from different sources in the network.

(2) The request type is XHR request. This is often referred to as an Ajax request. Not request image resources, JS files, CSS files, etc

(3) The browser feels insecure. The basic cause of cross-domain problems is the same origin policy of browsers. The same origin policy is an important security policy that restricts how an Origin document or script it loads can interact with resources from another source.

Note that the error occurs on the browser side. The request can be sent from the browser to the server normally, and the server can process the request, but there is an error when it comes back to the browser.

solution

The request and response urls are from different sources

  • Server agent

The request is ajax

  • To send the json

The browser doesn’t feel secure (the backend can still receive requests)

  • You can install a browser plug-inallow-control-allow-originBypass the same-origin policy.
  • Test with Postman software
  • CORS

JSONP- Basic implementation

The json profile

JSON with Padding is a technique for sending cross-domain requests using script tags. It is not an Ajax request per se, so there are no cross-domain issues.

Principle:

  • The SRC attribute of script can request external JS files. This request is not Ajax, and it has no cross-domain problems.
  • With the help ofscriptThe SRC tag requests the interface on the server.<script src="http://localhost:3000/get"
  • The interface on the server side returns a JavaScript script with the data to return.Res. End (" fn (data) ")

Implementation steps

  • Create a script tag and have SRC point to the interface address
  • Let the interface return the function call expression and pass in the data
  • Prepare corresponding functions at the front end

Make the SRC of the script tag point to the interface address

The front page


<html>
    <script src="http://localhost:3000/get"></script>
</html>
Copy the code

Note:

  • SRC in the script tag points to the address of a back-end interface. Since script tags do not cause cross-domain problems, requests are sent and received normally.
  • Instead of SRC pointing to a specific.js file, we just need to make sure that the return content of the address SRC points to is JS code, rather than SRC pointing directly to a.js file.
  • The content returned from the interface address will be the body of the script tag.

Let the interface return the function call expression and pass in the data

The back-end code

const express = require('express'); const app = express(); app.get('/get', (req, res) => { const data = JSON.stringify({a:1,b:2}) const fnStr = `fn(${data})` res.end(fnStr); Function call statement}) app.listen(3000, () => {console.log(' you can access this at http://localhost:3000... '); });Copy the code

Note:

  • The return value of the back-end interface is a special string: a deliberately spelled JS function call statement.

Prepare corresponding functions at the front end

Add fn functions to the page


<script>
    function fn(rs) {
        console.log(rs);
    }
</script>
<html>
    <script src="http://localhost:3000/get"></script>
</html>
Copy the code

The json in field

Jsonp in jQuery

Ajax in jquery has already encapsulated the JSONP approach and can be used directly.

Specifically, you add a dataType attribute to the Ajax request with a value of “jSONP”.

The following is an example:

Front page: add dataType attribute

$.ajax({ type: 'GET', url: 'http://localhost:4000/get', success: function (result) { console.log(result); }, dataType: 'jsonp' // Must specify dataType as jsonp});Copy the code

The backend interface

The Express framework already provides a method called JSONP to handle JSONP requests:

const express = require('express'); const app = express(); app.get('/get', (req, res) => { let data = {a:1,b:2} // res.json(data) res.jsonp(data) }) app.listen(3000, () => {console.log(' You can access it at http://localhost:3000... '); });Copy the code

Res.json, res.jsonp

CORS

CORS is a W3C standard, which stands for “Cross-origin Resource Sharing”. It allows browsers to issue XMLHttpRequest requests across source servers, overcoming the limitation that AJAX can only be used in the same source.

CORS requires both browser and server support. Currently, all browsers support this function. Internet Explorer cannot be lower than Internet Explorer 10(Internet Explorer 8 supports CORS through XDomainRequest).

Review again the description of cross-domain errors

Handwritten implementation

Cross-domain can be achieved by setting the header header in the requested route.

App.get ('/get', (req, res) => {// * indicates that any domain name is allowed to Access res.setheader (' access-Control-allow-origin ', // res.setheader (' access-Control-allow-origin ', 'http://www.xxx.com') res.send(date.now ().tostring ())})Copy the code
  • This solution does not require any changes from the client (the client does not change the code), just as the cross-domain problem does not exist.
  • Add one when the server respondsAccess-Control-Allow-OriginThe response of the head

Using cors

The main points of

  1. It is an NPM package to be downloaded separately using the NPM package CORS

    npm i cors

  2. As middleware in Express, note that the code should be at the top


var cors = require('cors')
app.use(cors())
Copy the code

You can remove res.setheader inside a single interface

Jsonp vs CORS comparison

Json:

  • Not ajax
  • Can only supportThe get method
  • Good compatibility

cors:

  • No additional modifications are needed to the front end, just assume that the cross-domain problem does not exist.
  • Ajax is
  • Support various types of requests (post,get….)
  • Poor browser support (standard browsers support it)

Expand the data

The options request

If cross-domain Ajax is not a simple request, opttions precheck requests are made first, and then the real request is sent.

reference

Jsonp principle analysis of jquery package

The principle of analysis

Step 1: Generate a random function name; And create this function (jQuery34109553463653123275_1565234364495);

Step 2: Dynamically create a script tag whose SRC is the address of the concatenated back-end interface and callback value. If there are other parameters, pass them normally

The third step: after the request is successful return, perform in the first step to create function (jQuery34109553463653123275_1565234364495). This function will eventually point to success in $.ajax({success:function(){}})

Step 4: Destroy the function created in step 1 and the script tag created in step 2

Debugging technique

The process described above is done dynamically. To see the effect, add breakpoint debugging. In the jquery source code, look for return jqXHR and add a breakpoint.

Include a mock code (interview, handwritten JSONP)