Cross domain commonplace

Time:2021-11-25

1、 Jsonp

  • <script></script>

The basic principle is through dynamic creationscriptLabel and then usesrcProperty (the back end can wrap the data with the callback function name for return), but pay attention toJSONPOnly supportGETRequest, not supportedPOSTRequest:

//Callback function
function showData (result) {
    //JSON object to string
    $('#text').val(JSON.stringify(result));
}
$(document).ready(function () {
    $('#btn').click(function () {
        //Enter a script into the header that initiates a cross domain request
        $('head').append('<script><\/script>');
    });
});
  • jQueryofJSONPrequest
$(document).ready(function () {
    $('#btn').click(function () {
        $.ajax({
            url: 'http://localhost:9090/student',
            type: 'GET',
            Datatype: 'jsonp', // specify the data type returned by the server
            Jsonpcallback: 'showdata', // callback function can also be specified
            success: function (data) {
                //JSON object to string
                $('#text').val(JSON.stringify(data));
            }
        });
    });
});

2、 CORS cross domain resource sharing

utilizenginxperhapsphpjavaOther backend language settings allow cross domain requests:

header('Access-Control-Allow-Origin: *'); //  Allow access from all sources
header('Access-Control-Allow-Method: POST,GET'); //  Ways to allow access

3、 Server agent

The browser has cross domain restrictions, but the server does not have cross domain problems, so the server can request the resources of the desired domain and return them to the client.

  • NodejsAct as an agent(eggjs)
async demo() {
    const { ctx: {inputs} } = this;
    //Third party interface address
    const url = 'http://api.map.baidu.com/location/ip';
    //Get third party interface
    const res = await this.ctx.curl(url, {
        method: 'POST',
        dataType: 'text',
        data: inputs
    });
    //Return data
    this.success({
        data: res.data~~~~
    });
}

4、 Nginx reverse proxy

In profilenginx.confAdd the following configuration to:

location / {  
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

    if ($request_method = 'OPTIONS') {
        return 204;
    }
}

More articles

Recommended Today

Apache sqoop

Source: dark horse big data 1.png From the standpoint of Apache, data flow can be divided into data import and export: Import: data import. RDBMS—–>Hadoop Export: data export. Hadoop—->RDBMS 1.2 sqoop installation The prerequisite for installing sqoop is that you already have a Java and Hadoop environment. Latest stable version: 1.4.6 Download the sqoop installation […]