What is cross-domain:

  • When the browser sends an Ajax request, it receives only the data resources that are responded to by the server in the same domain. So what is a codomain? Very simple, the protocol, domain name, port are all the same in the same domain, three conditions are inconsistent, are not the same domain, both cross domain.

The same origin policy is also called cross-domain prohibition policy

  • Prevents scripts loaded from one domain from obtaining or manipulating resources in another domain;

Actual operation:

  • Start a two-port server:

  • The server accessing port 8000 obtains a page, in which ajax is used to send requests to the server accessing port 9000.

jsonp

  • Javascript files are called on Web pages regardless of whether they are cross-domain or not (moreover, we also found that tags with “SRC” attribute have cross-domain capabilities, such as script, img, iframe). SRC’s ability to load remote data resources locally (images, JS code, etc.);

How do I use JSONP

  • Is in the remote server to try to dynamically put the data into the JS format text code segment, for the client to call and further processing; Adding script tags and SRC attributes dynamically in the foreground looks a lot like Ajax, but it has nothing to do with Ajax; In order to facilitate use and communication, an informal transport protocol was gradually formed, which was called JSONP.

  • One of the key points of this protocol is to allow the user to pass a callback argument to the server, which then returns the data wrapped around the JSON data as a function name, allowing the client to customize its own functions to automatically process the returned data.

index.html

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0"> <title>Document</title> </head> <body> </body> <! The core of jSONp: using SRC attributes to send requests, the server returns JAVASCRIPT code to call functions written in the front page.functionbackData(data){ alert(data); } </script> <! BackData (123) --> <! --> <script SRC ="http://127.0.0.1:9000/"> / / <! --> // <! -- <script src="Http://127.0.0.1:9000/getjson? callback=backData"> -->
  
</script>
</html>
Copy the code

8000 Server:

var fs = require('fs');
var url = require('url');
var http = require('http');


var server = http.createServer();

server.listen(8000, function () {
    console.log('8000 started successfully! ')
})

server.on('request'.function (req, res) {
    var urls = url.parse(req.url, true);

    if (req.method == 'GET') {
        if (urls.pathname == '/') {}else if (urls.pathname == '/gets') {

            res.end(' ');
        } else {

            fs.readFile('. ' + urls.pathname, function (err, data_str) {
                if(! err) { res.end(data_str); }else {
                    res.end(' ')}})}}else if (req.method == 'POST') {}})Copy the code

9000 server

var fs = require('fs');
var url = require('url');
var http = require('http');


var server = http.createServer();

server.listen(9000, function () {
    console.log('9000 started successfully! ')
})

server.on('request'.function (req, res) {
    var urls = url.parse(req.url, true);

    if (req.method == 'GET') {//1if (urls.pathname == '/') {
            var num = "123";
            // var num = "Text"; No good res. End ('backData('+ num+') ');

        } else if (urls.pathname == '/gets') {

            res.end('The browser is showing.'); //2.else if(urls.pathname == '/getjson'){

            var str =I don't need to know the name of this function.; // STR has no output // res.end(urls.query.callback+'('+str+') '); // the url can reach the function name because it is passed to res.end(urls.query.callback+)'('+'123'+') ');
            

        } else {

            fs.readFile('. ' + urls.pathname, function (err, data_str) {
                if(! err) { res.end(data_str); }else {
                    res.end(' '); }}}})else if (req.method == 'POST') {// Post requestif (urls.pathname == '/posts') {
            var d = ' ';

            req.on('data'.function (post_data) {
                d += post_data;
            })

            req.on('end'.function () {

                var obj = require('querystring').parse(d);

                if (obj.name == 'admin') {
                    res.end('repeat')}else {
                    res.end('norepeat')}})}}Copy the code

Second: Cross-domain resource sharing (CORS) mechanism

  • Recommended article: zhuanlan.zhihu.com/p/53996160

index.html

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
 
<input type="button"value="Button" >

</body>

<script>
     document.getElementsByTagName('input')[0].onclick = function(){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {if(xhr.readyState== 4 ){ alert(xhr.responseText); }} // simple request // xhr.open('get'.'http://127.0.0.1:9000/getcors'); // Request method: xhr.open('delete'.'http://127.0.0.1:9000/getcors');
        //
        // xhr.setRequestHeader('get'.'http://127.0.0.1:9000/getcors'); // request header // xhr.setrequesTheader ('kkkkk'.'http://127.0.0.1:9000/getcors');

        xhr.send();
    }

</script>
</html>
Copy the code

8000: the server

var fs = require('fs');
var url = require('url');
var http = require('http');


var server = http.createServer();

server.listen(8000, function () {
    console.log('8000 started successfully! ')
})

server.on('request'.function (req, res) {
    var urls = url.parse(req.url, true);

    if (req.method == 'GET') {
        if (urls.pathname == '/') {}else if (urls.pathname == '/gets') {

            res.end(' ');
        } else {

            fs.readFile('. ' + urls.pathname, function (err, data_str) {
                if(! err) { res.end(data_str); }else {
                    res.end(' ')}})}}else if (req.method == 'POST') {}})Copy the code

9000: Server

var fs = require('fs');
var url = require('url');
var http = require('http'); var server = http.createServer(); Server. listen(9000,function () {
    console.log('9000 started successfully! ')
})

server.on('request'.function (req, res) {
    var urls = url.parse(req.url, true); // Write it here: res.setheader ('Access-Control-Allow-Origin'.'http://127.0.0.1:8000');
    if (req.method == 'GET') {
        
        if (urls.pathname == '/') {}else if (urls.pathname == '/getcors') {// add the request header before returning // res.setheader ('Access-Control-Allow-Origin'.'http://127.0.0.1:8000');
            res.end('123456789');
           
        }else {

            fs.readFile('. ' + urls.pathname, function (err, data_str) {
                if(! err) { res.end(data_str); }else {
                    res.end(' '); }}}})else if (req.method == 'POST') {// Post requestif (urls.pathname == '/posts') {
            var d = ' ';

            req.on('data'.function (post_data) {
                d += post_data;
            })

            req.on('end'.function () {

                var obj = require('querystring').parse(d);

                if (obj.name == 'admin') {
                    res.end('repeat')}else {
                    res.end('norepeat')}})}}else if(req.method == 'OPTIONS'){// Are you allowed to send any type of request headers //'Access-Control-Allow-Headers' ,'DELETE has a lot more to add '
        // res.setHeader('Access-Control-Allow-Origin'.'http://127.0.0.1:8000');
       
        res.setHeader('Access-Control-Allow-Methods'.'DELETE');
        res.end(' ');
    }else if(req.method == 'DELETE'){
        res.end('1335881694');

    }else{}})Copy the code