html 跨域_常见跨域解决方案以及Ocelot 跨域配置
常見(jiàn)跨域解決方案以及Ocelot 跨域配置
Intro
我們?cè)谑褂们昂蠖朔蛛x的模式進(jìn)行開(kāi)發(fā)的時(shí)候,如果前端項(xiàng)目和api項(xiàng)目不是一個(gè)域名下往往會(huì)有跨域問(wèn)題。今天來(lái)介紹一下我們?cè)贠celot網(wǎng)關(guān)配置的跨域。
什么是跨域
跨域:
瀏覽器對(duì)于javascript的同源策略的限制,例如a.cn下面的js不能調(diào)用b.cn中的js,對(duì)象或數(shù)據(jù)(因?yàn)閍.cn和b.cn是不同域),所以跨域就出現(xiàn)了.
上面提到的,同域的概念又是什么呢??? 簡(jiǎn)單的解釋就是相同域名,端口相同,協(xié)議相同
同源策略:
請(qǐng)求的url地址,必須與瀏覽器上的url地址處于同域上,也就是域名,端口,協(xié)議相同.
比如:我在本地上的域名是study.cn,請(qǐng)求另外一個(gè)域名一段數(shù)據(jù)
這個(gè)時(shí)候在瀏覽器上會(huì)報(bào)錯(cuò):
這個(gè)就是同源策略的保護(hù),如果瀏覽器對(duì)javascript沒(méi)有同源策略的保護(hù),那么一些重要的機(jī)密網(wǎng)站將會(huì)很危險(xiǎn)~
study.cn/json/jsonp/jsonp.html
當(dāng)協(xié)議、子域名、主域名、端口號(hào)中任意一個(gè)不相同時(shí),都算作不同域。不同域之間相互請(qǐng)求資源,就算作“跨域”。
| http://study.cn/test/a.html | 同一域名,不同文件夾 | 成功 |
| http://study.cn/json/jsonp/jsonp.html | 同一域名,統(tǒng)一文件夾 | 成功 |
| http://a.study.cn/json/jsonp/jsonp.html | 不同域名,文件路徑相同 | 失敗 |
| http://study.cn:8080/json/jsonp/jsonp.html | 同一域名,不同端口 | 失敗 |
| https://study.cn/json/jsonp/jsonp.html | 同一域名,不同協(xié)議 | 失敗 |
跨域幾種常見(jiàn)的解決方案
解決跨域問(wèn)題有幾種常見(jiàn)的解決方案:
跨域資源共享(CORS)
通過(guò)在服務(wù)器端配置 CORS 策略即可,每門(mén)語(yǔ)言可能有不同的配置方式,但是從本質(zhì)上來(lái)說(shuō),最終都是在需要配置跨域的資源的Response上增加允許跨域的響應(yīng)頭,以實(shí)現(xiàn)瀏覽器跨域資源訪問(wèn),詳細(xì)可以參考MDN上的這篇CORS介紹
JSONP
JSONP 方式實(shí)際上返回的是一個(gè)callbak,通常為了減輕web服務(wù)器的負(fù)載,我們把js、css,img等靜態(tài)資源分離到另一臺(tái)獨(dú)立域名的服務(wù)器上,在html頁(yè)面中再通過(guò)相應(yīng)的標(biāo)簽從不同域名下加載靜態(tài)資源,而被瀏覽器允許,基于此原理,我們可以通過(guò)動(dòng)態(tài)創(chuàng)建script,再請(qǐng)求一個(gè)帶參網(wǎng)址實(shí)現(xiàn)跨域通信。
原生實(shí)現(xiàn):
var script = document.createElement('script');
script.type = 'text/javascript';
// 傳參一個(gè)回調(diào)函數(shù)名給后端,方便后端返回時(shí)執(zhí)行這個(gè)在前端定義的回調(diào)函數(shù)
script.src = 'http://www.domain2.com:8080/login?user=admin&callback=handleCallback';
document.head.appendChild(script);
// 回調(diào)執(zhí)行函數(shù)
function handleCallback(res) {
alert(JSON.stringify(res));
}
服務(wù)端返回如下(返回時(shí)即執(zhí)行全局函數(shù)):
handleCallback({"status": true, "user": "admin"})
jquery ajax
$.ajax({
url: 'http://www.domain2.com:8080/login',
type: 'get',
dataType: 'jsonp', // 請(qǐng)求方式為jsonp
jsonpCallback: "handleCallback", // 自定義回調(diào)函數(shù)名
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返回設(shè)置
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 請(qǐng)求
代理
前端代理
在現(xiàn)代化的前端開(kāi)發(fā)的時(shí)候往往可以配置開(kāi)發(fā)代理服務(wù)器,實(shí)際作用相當(dāng)于做了一個(gè)請(qǐng)求轉(zhuǎn)發(fā),但實(shí)際請(qǐng)求的api地址是沒(méi)有跨域問(wèn)題的,然后由實(shí)際請(qǐng)求的api服務(wù)器轉(zhuǎn)發(fā)請(qǐng)求到實(shí)際的存在跨域問(wèn)題的api地址。
angular 配置開(kāi)發(fā)代理可以參考 angular反向代理配置
后端代理
后端可以通過(guò)一個(gè)反向代理如(nginx),統(tǒng)一暴露一個(gè)服務(wù)地址,然后為所有的請(qǐng)求設(shè)置跨域配置,配置 CORS 響應(yīng)頭,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();
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();
這里擴(kuò)展了一個(gè) Ocelot pipeline 的配置,這樣我們可以直接很方便的直接在 Startup 里配置 Ocelot 的請(qǐng)求管道。
核心代碼:
ocelotBuilder.Use(async (context, next) =>
{
if (!context.DownstreamResponse.Headers.Exists(h => h.Key == HeaderNames.AccessControlAllowOrigin))
{
var allowedOrigins = Configuration.GetAppSetting("AllowedOrigins").SplitArray();
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 中間件后面添加這個(gè)中間件在響應(yīng)中增加跨域請(qǐng)求頭配置,這里先判斷了一下下面的api有沒(méi)有配置,如果已經(jīng)配置則不再配置,使用下游api的跨域配置,這樣一來(lái),只需要在網(wǎng)關(guān)配置指定的允許跨域訪問(wèn)的源即使下游api沒(méi)有設(shè)置跨域也是可以訪問(wèn)了
需要說(shuō)明一下的是如果想要這樣配置需要 Ocelot 13.2.0 以上的包,因?yàn)橹?HttpRequester 這個(gè)中間件沒(méi)有調(diào)用下一個(gè)中間件,詳見(jiàn) 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社區(qū)新聞,深度好文,歡迎訪問(wèn)公眾號(hào)文章匯總?http://www.csharpkit.com?
總結(jié)
以上是生活随笔為你收集整理的html 跨域_常见跨域解决方案以及Ocelot 跨域配置的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python怎么选择安装位置图片_怎么下
- 下一篇: javascript json_爬虫里总