首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用JSONP或CORS的跨域JavaScript调用

使用JSONP或CORS的跨域JavaScript调用
EN

Stack Overflow用户
提问于 2017-04-20 22:06:04
回答 2查看 17.4K关注 0票数 1

如何在客户端和服务器端使用jsonp和CORS实现网页上的跨域ajax调用。

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

EN

回答 2

Stack Overflow用户

发布于 2017-04-23 08:02:29

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

1.只使用JSONP而不使用CORS:如果使用JSONP,总是需要进行服务器端更改以获得带有callback方法的json响应。此外,要执行的javascript中必须存在callback方法。因此,在下面的示例中,当我们调用目标url时,如果我们得到的响应是myCallBackMethod({ "customerData": { "name": "testName", "age": 26 } }),那么我们必须有一个名称为myCallBackMethodjavascript method。使用jsonp、cookies can also be shared across domains

  • 在这种方法中,不需要在目标服务器的响应中设置任何标头来允许请求的域。
  • 本例中使用的callback方法是myCallBackMethod。此名称可以是除response jsonp string must match

javascript中的名称之外的任何名称

客户端/ javascript:

代码语言: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.只使用CORS,不使用JSONP,也不使用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:

代码语言: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;
  }

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

代码语言:javascript
复制
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。要获得跨请求页面和服务器的cookies,我们需要在客户端和服务器上添加以下属性。

客户端/javascript上的

代码语言:javascript
复制
xhrFields: {
    'withCredentials': true // tell the client to send the cookies if any for the requested domain
    }

服务器上的

代码语言:javascript
复制
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");

  • 这些更改允许客户端和服务器共享cookies.
  • However,如果在响应中使用报头Access-Control-Allow-Origin,则对报头Access-Control-Allow-Origin的值有限制。它应该是never be * if we want to use Access-Control-Allow-Credentials header。因此,请提供确切的域名。

服务器上的更新:

代码语言:javascript
复制
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方法)

代码语言: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
      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方法)

代码语言:javascript
复制
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("Access-Control-Allow-Origin", "www.mytestsite.com");

3.仅与CORS配合使用URL重写过滤器设置响应头:

如果应用程序使用url重写过滤器(大多数web应用程序都是这样),这将提供更容易的实现。不是遵循上面方法2中的最终服务器代码:(仅CORS方法),而是遵循下面的url来更改xml ( url重写过滤器)。

How to set origin or referer value which we got from request into the response-header using urlrewritefilter

为了快速参考,下面粘贴了相同的代码。

代码语言:javascript
复制
<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>

票数 10
EN

Stack Overflow用户

发布于 2018-09-29 03:23:28

如果你不能控制服务器端,你可以像我一样在

仅限客户端。

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

仅在客户端,解决方法是

使用dataType:'jsonp',

代码语言:javascript
复制
   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               
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43521856

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档