使用JSONP或CORS跨域JavaScript调用



如何在客户端和服务器中使用JSONP和CORS在网页上实现跨域AJAIN呼叫。

例如,在www.mytestsite.com上,要对www.otherdestinationserver.com进行AJAX调用,如何使用JSONPCORS实现?

最后,我在研究并浏览了所有其他帖子后找到了一些解决方案。我正在为这两种方法写答案。

1。仅使用JSONP没有CORS:

如果使用JSONP,总是需要更改服务器端以使用callback方法获得JSON响应。此外,callback方法必须在javascript中存在以执行。因此,在下面的示例中,当我们调用目标URL时,如果将响应作为myCallBackMethod({ "customerData": { "name": "testName", "age": 26 } }),则必须具有一个名称myCallBackMethodjavascript method。使用JSONP,cookies can also be shared across domains

  • 在这种方法中,无需设置目标服务器响应中的任何标头即可允许请求的域。
  • 此示例中使用的callback方法是myCallBackMethod。此名称可以是任何东西,除了javascriptresponse jsonp string must match中的名称

客户端/JavaScript:

function makeTheCall(queryString) {
    var destinationUrl = "www.otherdestinationserver.com";
    $.ajax({
      type: 'GET',
      url: destinationUrl + queryString,
      dataType: 'jsonp',
      jsonpCallback: 'myCallBackMethod',
      async: false, // this is by default false, so not need to mention
      crossDomain: true // tell the browser to allow cross domain calls.
     // success: successResopnse, jsonpCallback will call the successCallback
     // error: failureFunction jsonp does not support errorCallback. So cannot use this 
    });
  }
  window.myCallBackMethod = function(data) {
   successResponse(data);
  }
  
  successResponse = function(data) {
  //functionality goes here;
  }
  
  // the json response from the server when calling the url must be in the below format only.
  
  myCallBackMethod({ "customerData": { "name": "testName", "age": 26 } })

2。仅使用没有JSONP的CORS且没有URL重写:

如果使用CORS,总会有need to make changes on server and client/javascript。在这种方法中,no need to get any callback作为JSON响应的一部分。响应must be a pure json。但是,在目标服务器上进行适当的代码更改以使请求通过。因此,需要在response对象中设置header

客户端/JavaScript:

function makeTheCall(queryString) {
    var destinationUrl = "www.otherdestinationserver.com";
    $.ajax({
      type: 'GET',
      url: destinationUrl + queryString,
      dataType: 'json', // use json only, not jsonp
      crossDomain: true, // tell browser to allow cross domain.
      success: successResopnse,
      error: failureFunction
    });
  }
  
  successResponse = function(data) {
  //functionality goes here;
  }
  failureFunction = function(data) {
  //functionality goes here;
  }

在服务器上,添加下面的标题。

httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Here need to give the origin url (the url in the address bar of the page which is making request). Using * means allow any value
  • 但是,将上述代码添加到服务器中,服务器和请求的页面之间将不会共享任何cookie。要在请求的页面和服务器上获取cookie,我们需要在客户端和服务器上添加以下属性。

在客户端/javascript上:

xhrFields: {
    'withCredentials': true // tell the client to send the cookies if any for the requested domain
    }

在服务器上:

httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
  • 这些更改允许客户端和服务器共享cookie。
  • 但是,如果在响应中使用标头Access-Control-Allow-Credentials,则标题Access-Control-Allow-Origin的值有一个限制。它应该never be * if we want to use Access-Control-Allow-Credentials header。因此给出确切的域名。

在服务器上更新:

httpServletResponse.setHeader("Access-Control-Allow-Origin", "www.mytestsite.com"); // Give the origin url (the url in the address bar of the page which is making request).

最终客户端/JavaScript :(仅CORS方法(

function makeTheCall(queryString) {
    var destinationUrl = www.otherdestinationserver.com;
    $.ajax({
      type: 'GET',
      url: destinationUrl + queryString,
      dataType: 'json', // use json only, not jsonp
      crossDomain: true, // tell browser to allow cross domain
      xhrFields: {
         'withCredentials': true // tell the client to send the cookies if any for the requested domain
      },
      success: successResopnse,
      error: failureFunction
    });
  }
  
  successResponse = function(data) {
  //functionality goes here;
  }
  failureFunction = function(data) {
  //functionality goes here;
  }

最终服务器代码:(仅CORS方法(

httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("Access-Control-Allow-Origin", "www.mytestsite.com");

3。仅将CORS与URL重写过滤器设置响应标头使用:

如果应用程序使用URL重写过滤器(大多数是所有Web应用程序所做的(,这将使实现更加容易。而不是遵循最终服务器代码:(仅CORS方法(在上面的方法2中,请按以下URL在XML(URL重写过滤器(上进行更改。

如何使用urlrewritefilter

将我们从请求中获得的来源或推荐人值设置

粘贴的相同代码以供快速参考。

<rule enabled="true" match-type="regex">
<name>Enabling CORS Headers</name>
<from>^/path/someMorePath.*$</from>
<condition name="origin" operator="equal">([a-z]+)</condition>
<set type="response-header" name="Access-Control-Allow-Origin">%1</set>
<set type="response-header" name="Access-Control-Allow-Credentials">true</set>

仅客户端。

如果您可以控制服务器端,则可以使用服务器端解决方案。我不是在这里讨论。

仅在客户端,工作是

使用datatype:'jsonp',

   async function get_ajax_data(){
       var _reprojected_lat_lng = await $.ajax({
                                type: 'GET',
                                dataType: 'jsonp',
                                data: {},
                                url: _reprojection_url,
                                error: function (jqXHR, textStatus, errorThrown) {
                                    console.log(jqXHR)
                                },
                                success: function (data) {
                                    console.log(data);

                                    // note: data is already json type, you just specify dataType: jsonp
                                    return data;
                                }
                            });


 } // function               

最新更新