跨域(jsonp cors)

來源:互聯網
上載者:User

標籤:oca   ++   option   head   logs   連接埠   12px   get   netcore   

同源策略它是由NetScape提出的一個著名的安全性原則。

瀏覽器執行js,會檢查它屬於哪個頁面,如果不是同源頁面,不會被執行。

由於瀏覽器的同源策略,只要發送請求url與頁面地址有不同的即為跨域。只要協議、網域名稱、連接埠任何一個不同,就是不同的域。 常見的解決方案有: jsonp 跨域資源共用(CORS) 使用html5的window.postMessage 通過修改document.domain  使用window.name 1.jsonp      jsonp 全稱是JSON with Padding,是為瞭解決跨域請求資源而產生的解決方案,是一種依靠開發人員創造出的一種非官方跨域資料互動協議     利用了<script>標籤可以連結到不同源的js指令碼,來到達跨域目的.(js指令碼、css樣式 、圖片可以與本身頁面不同源。)
  <!-- js檔案載入成功後會執行我們在url參數中指定的函數,    並且會把我們需要的json資料作為參數傳入。所以jsonp是需要伺服器端的頁面進行相應的配合的。 -->    <script type="text/javascript">        function callback(jsondata) {            console.log(jsondata);        }    </script>    <script src="http://localhost:5000/api/test/get/callback?callback=callback"></script>
通過ajax調用實現
  $(function () {            $("#btn").on("click", function () {                $.ajax({                    url: "http://localhost:5000/api/test/get/successCallback",                    dataType: ‘jsonp‘,                    jsonp: ‘mycallback‘,                    jsonpCallback: ‘successCallback‘,                    success: function (data) {                        $(‘ul li‘).remove();                        var ul = $("#ul");                        for (var index = 0; index < data.length; index++) {                            var element = data[index];                            ul.append("<li>" + element + "</li>");                        }                    },                    error: function(err){                        console.log(‘error‘);                        console.log(err.status);                    }                                    });            })        });
?優點:可以實現跨域,相容性好,回呼函數在本地處理?缺點:只支援get;需要在伺服器端增加callback處理;出錯,不會有狀態代碼。 2.CORS跨域資源共用( CORS )機制允許 Web 應用程式伺服器進行跨域存取控制,從而使跨域資料轉送得以安全進行。瀏覽器支援在 API 容器中(例如  XMLHttpRequest 或 Fetch )使用 CORS,以降低跨域 HTTP 要求所帶來的風險。

跨域資源共用標準( cross-origin sharing standard )允許在下列情境中使用跨域 HTTP 要求:

  • 前文提到的由 XMLHttpRequest 或 Fetch 發起的跨域 HTTP 要求。
  • Web 字型 (CSS 中通過 @font-face 使用跨域字型資源), 因此,網站就發行就緒 TrueType 字型資源,並只允許已授權網站進行跨站調用。
  • WebGL 貼圖
  • 使用 drawImage 將 Images/video 畫面繪製到 canvas
  • 樣式表(使用 CSSOM)
  • Scripts (未處理的異常)

需要在伺服器端進行設定,以 .netCore為例:

 public void ConfigureServices(IServiceCollection services)        {            services.AddMvc();            services.AddCors(options => options.AddPolicy("AllowDomain",            builder =>            {                builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();            }));        }        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)        {             app.UseCors("AllowDomain");            loggerFactory.AddConsole(Configuration.GetSection("Logging"));            loggerFactory.AddDebug();            app.UseMvc();        }

 

   1.簡單請求

      使用GET,HEAD,POST(Content-Type 為 text/plain  multipart/form-data  application/x-www-form-urlencoded)

      請求過程如

 

代碼:
  $("#simplebtnpost").on("click", function () {                $.ajax({                    type: "post",                    data:{name:‘1111‘},                    url: "http://localhost:5000/api/test/post",                    success: function (datas) {                        $(‘ul‘).empty();                        $.each(datas, function (element) {                            $(‘ul‘).append("<li>" + datas[element] + "</li>");                        });                    }                });            })

   2.預檢請求

     與前述簡單請求不同,“需預檢的請求”要求必須首先使用 OPTIONS  方法發起一個預檢請求到伺服器,以獲知伺服器是否允許該實際請求。"預檢請求“的使用,可以避免跨域請求對伺服器的使用者資料產生未預期的影響。

當請求滿足下述任一條件時,即應首先發送預檢請求:

  • 使用了下面任一 HTTP 方法:PUT;DELETE;CONNECT;OPTIONS;TRACE;PATCH
  • 人為設定了對 CORS 安全的首部欄位集合之外的其他首部欄位。該集合為:Accept;Accept-Language;Content-Language;Content-Type (but note the additional requirements below);DPR;Downlink;Save-Data;Viewport-Width;Width
  •  Content-Type 的值不屬於下列之一:;application/x-www-form-urlencoded;multipart/form-data;text/plain

請求過程:

 代碼:
            $("#btnput").on("click", function () {                $.ajax({                    type: "put",                    url: "http://localhost:5000/api/test/put",                    data: {                        name: ‘測試‘,                    },                    dataType: "json",                    ContentType: "application/json",                    beforeSend: function (request) {                        request.setRequestHeader("Content-type",                            "application/json; charset=utf-8");                    },                    success: function (datas) {                        $(‘ul‘).empty();                        $.each(datas, function (element) {                            $(‘ul‘).append("<li>" + datas[element] + "</li>");                        });                    }                });            })

 

Access-Control-Allow-Origin

響應首部中可以攜帶一個 Access-Control-Allow-Origin 欄位,其文法如下:

Access-Control-Allow-Origin: <origin> | *

Access-Control-Allow-Methods

Access-Control-Allow-Methods 首部欄位用於預檢請求的響應。其指明了實際請求所允許使用的 HTTP 方法。

Access-Control-Allow-Methods: <method>[, <method>]*

Access-Control-Allow-Headers

Access-Control-Allow-Headers 首部欄位用於預檢請求的響應。其指明了實際請求中允許攜帶的首部欄位。

Access-Control-Allow-Headers: <field-name>[, <field-name>]*

 
Access-Control-Allow-Credentials

Access-Control-Allow-Credentials 首部欄位用於預檢請求的響應,表明伺服器是否允許 credentials 標誌設定為 true 的請求。

Credentials可以是 cookies, authorization headers 或 TLS client certificates.

Access-Control-Allow-Credentials: true

 
Access-Control-Expose-Headers

Access-Control-Expose-Headers 首部欄位指定了服務端允許的首部欄位集合。(預設情況是以下六種簡單響應首部(simple response headers)):cache-control,

content-language,Content-Type,Expires,Last-Modified,Pragma)

Access-Control-Expose-Headers: X-My-Custom-Header, X-Another-Custom-Header

 

 

 

 

 
 
 
 
        

 

跨域(jsonp cors)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.