日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

常见跨域解决方案以及Ocelot 跨域配置

發布時間:2023/12/4 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 常见跨域解决方案以及Ocelot 跨域配置 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

常見跨域解決方案以及Ocelot 跨域配置

Intro

我們在使用前后端分離的模式進行開發的時候,如果前端項目和api項目不是一個域名下往往會有跨域問題。今天來介紹一下我們在Ocelot網關配置的跨域。

什么是跨域

跨域:

瀏覽器對于javascript的同源策略的限制,例如a.cn下面的js不能調用b.cn中的js,對象或數據(因為a.cn和b.cn是不同域),所以跨域就出現了.

上面提到的,同域的概念又是什么呢??? 簡單的解釋就是相同域名,端口相同,協議相同

同源策略:

請求的url地址,必須與瀏覽器上的url地址處于同域上,也就是域名,端口,協議相同.

比如:我在本地上的域名是study.cn,請求另外一個域名一段數據

這個時候在瀏覽器上會報錯:

這個就是同源策略的保護,如果瀏覽器對javascript沒有同源策略的保護,那么一些重要的機密網站將會很危險~

study.cn/json/jsonp/jsonp.html

當協議、子域名、主域名、端口號中任意一個不相同時,都算作不同域。不同域之間相互請求資源,就算作“跨域”。

請求地址形式結果
http://study.cn/test/a.html同一域名,不同文件夾成功
http://study.cn/json/jsonp/jsonp.html同一域名,統一文件夾成功
http://a.study.cn/json/jsonp/jsonp.html不同域名,文件路徑相同失敗
http://study.cn:8080/json/jsonp/jsonp.html同一域名,不同端口失敗
https://study.cn/json/jsonp/jsonp.html同一域名,不同協議失敗

跨域幾種常見的解決方案

解決跨域問題有幾種常見的解決方案:

跨域資源共享(CORS)

通過在服務器端配置 CORS 策略即可,每門語言可能有不同的配置方式,但是從本質上來說,最終都是在需要配置跨域的資源的Response上增加允許跨域的響應頭,以實現瀏覽器跨域資源訪問,詳細可以參考MDN上的這篇CORS介紹

JSONP

JSONP 方式實際上返回的是一個callbak,通常為了減輕web服務器的負載,我們把js、css,img等靜態資源分離到另一臺獨立域名的服務器上,在html頁面中再通過相應的標簽從不同域名下加載靜態資源,而被瀏覽器允許,基于此原理,我們可以通過動態創建script,再請求一個帶參網址實現跨域通信。

原生實現:

  • <script>

  • var script = document.createElement('script');

  • script.type = 'text/javascript';


  • // 傳參一個回調函數名給后端,方便后端返回時執行這個在前端定義的回調函數

  • script.src = 'http://www.domain2.com:8080/login?user=admin&callback=handleCallback';

  • document.head.appendChild(script);


  • // 回調執行函數

  • function handleCallback(res) {

  • alert(JSON.stringify(res));

  • }

  • </script>

  • 服務端返回如下(返回時即執行全局函數):

  • handleCallback({"status": true, "user": "admin"})

  • jquery ajax

  • $.ajax({

  • url: 'http://www.domain2.com:8080/login',

  • type: 'get',

  • dataType: 'jsonp', // 請求方式為jsonp

  • jsonpCallback: "handleCallback", // 自定義回調函數名

  • data: {}

  • });

  • 后端 node.js 代碼示例:

  • var querystring = require('querystring');

  • var http = require('http');

  • var server = http.createServer();


  • server.on('request', function(req, res) {

  • var params = qs.parse(req.url.split('?')[1]);

  • var fn = params.callback;


  • // jsonp返回設置

  • res.writeHead(200, { 'Content-Type': 'text/javascript' });

  • res.write(fn + '(' + JSON.stringify(params) + ')');


  • res.end();

  • });


  • server.listen('8080');

  • console.log('Server is running at port 8080...');

  • JSONP 只支持 GET 請求

    代理

    前端代理

    在現代化的前端開發的時候往往可以配置開發代理服務器,實際作用相當于做了一個請求轉發,但實際請求的api地址是沒有跨域問題的,然后由實際請求的api服務器轉發請求到實際的存在跨域問題的api地址。

    angular 配置開發代理可以參考 angular反向代理配置

    后端代理

    后端可以通過一個反向代理如(nginx),統一暴露一個服務地址,然后為所有的請求設置跨域配置,配置 CORS 響應頭,Ocelot是ApiGateway,也可以算是api的反向代理,但不僅僅如此。

    Ocelot 跨域配置

    示例代碼:

  • app.UseOcelot((ocelotBuilder, pipelineConfiguration) =>

  • {

  • // This is registered to catch any global exceptions that are not handled

  • // It also sets the Request Id if anything is set globally

  • ocelotBuilder.UseExceptionHandlerMiddleware();

  • // Allow the user to respond with absolutely anything they want.

  • if (pipelineConfiguration.PreErrorResponderMiddleware != null)

  • {

  • ocelotBuilder.Use(pipelineConfiguration.PreErrorResponderMiddleware);

  • }

  • // This is registered first so it can catch any errors and issue an appropriate response

  • ocelotBuilder.UseResponderMiddleware();

  • ocelotBuilder.UseDownstreamRouteFinderMiddleware();

  • ocelotBuilder.UseDownstreamRequestInitialiser();

  • ocelotBuilder.UseRequestIdMiddleware();

  • ocelotBuilder.UseMiddleware<ClaimsToHeadersMiddleware>();

  • ocelotBuilder.UseLoadBalancingMiddleware();

  • ocelotBuilder.UseDownstreamUrlCreatorMiddleware();

  • ocelotBuilder.UseOutputCacheMiddleware();

  • ocelotBuilder.UseMiddleware<HttpRequesterMiddleware>();

  • // cors headers

  • ocelotBuilder.Use(async (context, next) =>

  • {

  • if (!context.DownstreamResponse.Headers.Exists(h => h.Key == HeaderNames.AccessControlAllowOrigin))

  • {

  • var allowedOrigins = Configuration.GetAppSetting("AllowedOrigins").SplitArray<string>();

  • context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlAllowOrigin, allowedOrigins.Length == 0 ? new[] { "*" } : allowedOrigins));

  • context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlAllowHeaders, new[] { "*" }));

  • context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlRequestMethod, new[] { "*" }));

  • }

  • await next();

  • });

  • })

  • .Wait();

  • 這里擴展了一個 Ocelot pipeline 的配置,這樣我們可以直接很方便的直接在 Startup 里配置 Ocelot 的請求管道。

    核心代碼:

  • ocelotBuilder.Use(async (context, next) =>

  • {

  • if (!context.DownstreamResponse.Headers.Exists(h => h.Key == HeaderNames.AccessControlAllowOrigin))

  • {

  • var allowedOrigins = Configuration.GetAppSetting("AllowedOrigins").SplitArray<string>();

  • context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlAllowOrigin, allowedOrigins.Length == 0 ? new[] { "*" } : allowedOrigins));

  • context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlAllowHeaders, new[] { "*" }));

  • context.DownstreamResponse.Headers.Add(new Header(HeaderNames.AccessControlRequestMethod, new[] { "*" }));

  • }

  • await next();

  • });

  • 在 HttpRequester 中間件后面添加這個中間件在響應中增加跨域請求頭配置,這里先判斷了一下下面的api有沒有配置,如果已經配置則不再配置,使用下游api的跨域配置,這樣一來,只需要在網關配置指定的允許跨域訪問的源即使下游api沒有設置跨域也是可以訪問了

    需要說明一下的是如果想要這樣配置需要 Ocelot 13.2.0 以上的包,因為之前 HttpRequester 這個中間件沒有調用下一個中間件,詳見 https://github.com/ThreeMammals/Ocelot/pull/830

    Reference

    • https://developer.mozilla.org/zh-CN/docs/Web/HTTP/AccesscontrolCORS

    • https://segmentfault.com/a/1190000011145364

    • https://github.com/ThreeMammals/Ocelot/pull/830

    .NET社區新聞,深度好文,歡迎訪問公眾號文章匯總?http://www.csharpkit.com?


    總結

    以上是生活随笔為你收集整理的常见跨域解决方案以及Ocelot 跨域配置的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。