Why are there cross-domain problems?

Because all javascript-enabled browsers have a security policy called the same origin policy. The specific strategies are not discussed in this chapter. This security policy prevents cross-domain requests.

What is cross-domain?

Cross-domain is basically when you request a resource of ‘http://localhost:3001’ with an ‘http://localhost:3000’ (and vice versa). Our browser will kindly tell us:

Fetch is used here

But most of the time, we particularly need to cross domain, so there is a famous JSONP in the market to solve the cross domain problem.

How is JSONP implemented across domains?

The implementation of JSONP follows a principle:

Js files can be downloaded without being restricted by security policies

So, we can add the resource we want to request at the top of the HTML, for example:

<script type="text/javascript" src="http://localhost:3000/test.js></script>

By checking the browser network, this resource is requested, cross domain also successful!

Jsonp is cross-domain through this principle, but not only this.

Simple code to implement JSONP across domains

As we all know, jSONP cross-domain requires callback functions.

We pass the back function that’s implemented locally, okay? callback=back

<script>
    function back(data) {
        console.log(data);
    }
</script>
       
<script type="text/javascript" src="http://localhost:3000/test.js? callback=back"></script>
  
Copy the code

In http://localhost:3000/test.js, we only need to perform the back function:

back({message:"success"});

Copy the code

And returns JSON

{ 
    message:"success"
}
Copy the code

Convention callback names are important! Convention callback names are important! Convention callback names are important!


Extra little details

If I in http://localhost:3000/test.js, I don’t have to we agreed back the callback function name, so we won’t print to control what, for example, I at the moment:

say({message:"success"});
Copy the code

“Say” was not defined so the console reported an error.

Similarly, if you repeat the definition

const back = ({message:"success"});
Copy the code

Also error:

It’s all about grammar!