簡體   English   中英

使用JSONP或CORS進行跨域JavaScript調用

[英]Cross Domain JavaScript calls using JSONP or CORS

如何在客戶端和服務器中使用jsonp和CORS在網頁上實現跨域ajax調用。

例如,在www.mytestsite.com ,要對www.otherdestinationserver.com進行ajax調用,如何使用JSONPCORS實現?

最后,我在研究完所有其他帖子后找到了一些解決方案。 我正在為這兩種方法寫答案。

1.僅在沒有CORS的情況下使用JSONP:

如果使用JSONP,則始終需要進行服務器端更改以使用callback方法獲取json響應。 此外, callback方法必須存在於javascript才能執行。 所以在下面的例子中,當我們調用目標url時,如果我們得到響應為myCallBackMethod({ "customerData": { "name": "testName", "age": 26 } }) ,那么我們必須有一個javascript method名為myCallBackMethod javascript method 使用jsonp, cookies can also be shared across domains

  • 在此方法中,無需在目標服務器的響應中設置任何標頭以允許請求的域。
  • 此示例中使用的callback方法是myCallBackMethod 此名稱可以是任何內容,除了javascript的名稱和response 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且沒有URL REWRITES的情況下使用CORS:

如果使用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 headernever be * if we want to use Access-Control-Allow-Credentials header應該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 REWRITE FILTER設置RESPONSE HEADERS:

如果應用程序使用url重寫過濾器(主要是所有Web應用程序都使用),這將使實現更容易。 在上面的方法2中,不是遵循最終服務器代碼:(僅CORS方法) ,而是按照以下URL更改xml(url重寫過濾器)。

如何使用urlrewritefilter將我們從請求獲得的origin或referer值設置到response-header中

下面粘貼相同的代碼以供快速參考。

<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               

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM