简体   繁体   English

跨域读阻塞 (CORB)

[英]Cross-Origin Read Blocking (CORB)

I have called third party API using Jquery AJAX.我已经使用 Jquery AJAX 调用了第三方 API。 I am getting following error in console:我在控制台中收到以下错误:

Cross-Origin Read Blocking (CORB) blocked cross-origin response MY URL with MIME type application/json.跨域读取阻止 (CORB) 阻止了 MIME 类型为 application/json 的跨域响应我的 URL See https://www.chromestatus.com/feature/5629709824032768 for more details.有关详细信息,请参阅https://www.chromestatus.com/feature/5629709824032768

I have used following code for Ajax call :我为 Ajax 调用使用了以下代码:

$.ajax({
  type: 'GET',
  url: My Url,
  contentType: 'application/json',
  dataType:'jsonp',
  responseType:'application/json',
  xhrFields: {
    withCredentials: false
  },
  headers: {
    'Access-Control-Allow-Credentials' : true,
    'Access-Control-Allow-Origin':'*',
    'Access-Control-Allow-Methods':'GET',
    'Access-Control-Allow-Headers':'application/json',
  },
  success: function(data) {
    console.log(data);
  },
  error: function(error) {
    console.log("FAIL....=================");
  }
});

When I checked in Fiddler, I have got the data in response but not in Ajax success method.当我签入 Fiddler 时,我得到了响应数据,但没有在 Ajax 成功方法中。

Please help me out.请帮帮我。

 dataType:'jsonp',

You are making a JSONP request, but the server is responding with JSON.您正在发出 JSONP 请求,但服务器正在响应 JSON。

The browser is refusing to try to treat the JSON as JSONP because it would be a security risk.浏览器拒绝尝试将 JSON 视为 JSONP,因为这会带来安全风险。 (If the browser did try to treat the JSON as JSONP then it would, at best, fail). (如果浏览器确实尝试将 JSON 视为 JSONP,那么它充其量只会失败)。

See this question for more details on what JSONP is.有关 JSONP 是什么的更多详细信息,请参阅此问题 Note that is a nasty hack to work around the Same Origin Policy that was used before CORS was available.请注意,要解决在 CORS 可用之前使用的同源策略的问题,这是一个令人讨厌的 hack。 CORS is a much cleaner, safer, and more powerful solution to the problem. CORS 是一种更清洁、更安全、更强大的解决方案。


It looks like you are trying to make a cross-origin request and are throwing everything you can think of at it in one massive pile of conflicting instructions.看起来你正试图提出一个跨域请求,并将你能想到的所有东西都扔进一大堆相互冲突的指令中。

You need to understand how the Same Origin policy works.您需要了解同源策略的工作原理。

See this question for an in-depth guide.有关深入指南,请参阅此问题


Now a few notes about your code:现在有一些关于您的代码的注释:

 contentType: 'application/json',
  • This is ignored when you use JSONP当您使用 JSONP 时,这将被忽略
  • You are making a GET request.您正在发出 GET 请求。 There is no request body to describe the type of.没有描述类型的请求正文。
  • This will make a cross-origin request non-simple, meaning that as well as basic CORS permissions, you also need to deal with a pre-flight.这将使跨域请求变得不简单,这意味着除了基本的 CORS 权限外,您还需要处理预飞行。

Remove that.删除它。

 dataType:'jsonp',
  • The server is not responding with JSONP.服务器没有响应 JSONP。

Remove this.删除这个。 (You could make the server respond with JSONP instead, but CORS is better). (您可以让服务器使用 JSONP 进行响应,但 CORS 更好)。

 responseType:'application/json',

This is not an option supported by jQuery.ajax.这不是 jQuery.ajax 支持的选项。 Remove this.删除这个。

xhrFields: { withCredentials: false }, xhrFields: { withCredentials: false },

This is the default.这是默认设置。 Unless you are setting it to true with ajaxSetup, remove this.除非您使用 ajaxSetup 将其设置为 true,否则请删除它。

 headers: { 'Access-Control-Allow-Credentials' : true, 'Access-Control-Allow-Origin':'*', 'Access-Control-Allow-Methods':'GET', 'Access-Control-Allow-Headers':'application/json', },
  • These are response headers.这些是响应标头。 They belong on the response, not the request.它们属于响应,而不是请求。
  • This will make a cross-origin request non-simple, meaning that as well as basic CORS permissions, you also need to deal with a pre-flight.这将使跨域请求变得不简单,这意味着除了基本的 CORS 权限外,您还需要处理预飞行。

In most cases, the blocked response should not affect the web page's behavior and the CORB error message can be safely ignored.在大多数情况下,被阻止的响应不应影响网页的行为,并且可以安全地忽略 CORB 错误消息。 For example, the warning may occur in cases when the body of the blocked response was empty already, or when the response was going to be delivered to a context that can't handle it (eg, a HTML document such as a 404 error page being delivered to an tag).例如,当被阻止的响应的主体已经为空时,或者当响应将被传递到无法处理它的上下文(例如,HTML 文档,如 404 错误页面)时,可能会出现警告被传送到标签)。

https://www.chromium.org/Home/chromium-security/corb-for-developers https://www.chromium.org/Home/chromium-security/corb-for-developers

I had to clean my browser's cache, I was reading in this link, that, if the request get a empty response, we get this warning error.我必须清理浏览器的缓存,我正在阅读此链接,如果请求得到空响应,我们会收到此警告错误。 I was getting some CORS on my request, and so the response of this request got empty, All I had to do was clear the browser's cache, and the CORS got away.我的请求得到了一些 CORS,所以这个请求的响应是空的,我所要做的就是清除浏览器的缓存,然后 CORS 就消失了。 I was receiving CORS because the chrome had saved the PORT number on the cache, The server would just accept localhost:3010 and I was doing localhost:3002 , because of the cache.我收到 CORS 是因为 chrome 已将 PORT 号保存在缓存中,由于缓存,服务器只会接受localhost:3010而我正在做localhost:3002

Return response with header 'Access-Control-Allow-Origin:*' Check below code for the Php server response.返回带有标题'Access-Control-Allow-Origin:*'的响应检查以下代码以获取Php服务器响应。

<?php header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
echo json_encode($phparray); 

You have to add CORS on the server side:您必须在服务器端添加 CORS:

If you are using nodeJS then:如果您使用的是nodeJS ,那么:

First you need to install cors by using below command :首先,您需要使用以下命令安装cors

npm install cors --save

Now add the following code to your app starting file like ( app.js or server.js )现在将以下代码添加到您的应用程序启动文件中,例如( app.js or server.js

var express = require('express');
var app = express();

var cors = require('cors');
var bodyParser = require('body-parser');

//enables cors
app.use(cors({
  'allowedHeaders': ['sessionId', 'Content-Type'],
  'exposedHeaders': ['sessionId'],
  'origin': '*',
  'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
  'preflightContinue': false
}));

require('./router/index')(app);

It's not clear from the question, but assuming this is something happening on a development or test client, and given that you are already using Fiddler you can have Fiddler respond with an allow response:问题尚不清楚,但假设这是在开发或测试客户端上发生的事情,并且鉴于您已经在使用 Fiddler,您可以让 Fiddler 响应允许响应:

  • Select the problem request in Fiddler在 Fiddler 中选择问题请求
  • Open the AutoResponder tab打开“ AutoResponder选项卡
  • Click Add Rule and edit the rule to:单击Add Rule并将规则编辑为:
    • Method:OPTIONS server url here , eg Method:OPTIONS http://localhost Method:OPTIONS server url here , eg Method:OPTIONS http://localhost
    • *CORSPreflightAllow
  • Check Unmatched requests passthrough检查Unmatched requests passthrough
  • Check Enable Rules检查Enable Rules

A couple notes:几点注意事项:

  1. Obviously this is only a solution for development/testing where it isn't possible/practical to modify the API service显然,这只是一种开发/测试解决方案,无法/不切实际地修改 API 服务
  2. Check that any agreements you have with the third-party API provider allow you to do this检查您与第三方 API 提供商签订的任何协议是否允许您执行此操作
  3. As others have noted, this is part of how CORS works, and eventually the header will need to be set on the API server.正如其他人所指出的,这是 CORS 工作原理的一部分,最终需要在 API 服务器上设置标头。 If you control that server, you can set the headers yourself.如果您控制该服务器,则可以自己设置标头。 In this case since it is a third party service, I can only assume they have some mechanism via which you are able to provide them with the URL of the originating site and they will update their service accordingly to respond with the correct headers.在这种情况下,由于它是第三方服务,我只能假设他们有某种机制,您可以通过这些机制向他们提供原始站点的 URL,并且他们将相应地更新其服务以使用正确的标头进行响应。

If you are working on localhost, try this, this one the only extension and method that worked for me (Angular, only javascript, no php)如果您在本地主机上工作,试试这个,这是唯一对我有用的扩展和方法(Angular,只有 javascript,没有 php)

https://chrome.google.com/webstore/detail/moesif-orign-cors-changer/digfbfaphojjndkpccljibejjbppifbc/related?hl=en https://chrome.google.com/webstore/detail/moesif-orign-cors-changer/digfbfaphojjndkpccljibejjbppifbc/related?hl=en

In a Chrome extension, you can use在 Chrome 扩展程序中,您可以使用

chrome.webRequest.onHeadersReceived.addListener

to rewrite the server response headers.重写服务器响应标头。 You can either replace an existing header or add an additional header.您可以替换现有标题或添加其他标题。 This is the header you want:这是你想要的标题:

Access-Control-Allow-Origin: *

https://developers.chrome.com/extensions/webRequest#event-onHeadersReceived https://developers.chrome.com/extensions/webRequest#event-onHeadersReceived

I was stuck on CORB issues, and this fixed it for me.我被困在CORB问题上,这为我解决了这个问题。

have you tried changing the dataType in your ajax request from jsonp to json ?您是否尝试过将 ajax 请求中的dataTypejsonp更改为json that fixed it in my case.在我的情况下解决了它。

There is an edge case worth mentioning in this context: Chrome (some versions, at least) checks CORS preflights using the algorithm set up for CORB .在这种情况下,有一个值得一提的边缘案例:Chrome(至少某些版本)使用为 CORB 设置的算法检查 CORS 预检 IMO, this is a bit silly because preflights don't seem to affect the CORB threat model, and CORB seems designed to be orthogonal to CORS. IMO,这有点傻,因为预检似乎不会影响 CORB 威胁模型,而且 CORB 似乎被设计为与 CORS 正交。 Also, the body of a CORS preflight is not accessible, so there is no negative consequence just an irritating warning.此外,无法访问 CORS 预检的主体,因此没有负面后果,只是一个恼人的警告。

Anyway, check that your CORS preflight responses (OPTIONS method responses) don't have a body (204) .无论如何,请检查您的 CORS 预检响应(OPTIONS 方法响应)是否没有正文 (204) An empty 200 with content type application/octet-stream and length zero worked well here too.内容类型为 application/octet-stream 和长度为零的空 200 在这里也很有效。

You can confirm if this is the case you are hitting by counting CORB warnings vs. OPTIONS responses with a message body.您可以通过使用消息正文计算 CORB 警告与 OPTIONS 响应来确认您是否遇到这种情况。

It seems that this warning occured when sending an empty response with a 200.似乎在发送带有 200 的空响应时发生了此警告。

This configuration in my .htaccess display the warning on Chrome:我的.htaccess中的此配置在 Chrome 上显示警告:

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST,GET,HEAD,OPTIONS,PUT,DELETE"
Header always set Access-Control-Allow-Headers "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization"

RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]

But changing the last line to但是将最后一行更改为

RewriteRule .* / [R=204,L]

resolve the issue!解决问题!

Response headers are generally set on the server.响应头通常设置在服务器上。 Set 'Access-Control-Allow-Headers' to 'Content-Type' on server side在服务器端将'Access-Control-Allow-Headers'设置为'Content-Type'

Cross-Origin Read Blocking (CORB), an algorithm by which dubious cross-origin resource loads may be identified and blocked by web browsers before they reach the web page..It is designed to prevent the browser from delivering certain cross-origin network responses to a web page. Cross-Origin Read Blocking (CORB),一种算法,通过该算法,Web 浏览器可以识别并阻止可疑的跨源资源加载到达网页之前。它旨在防止浏览器提供某些跨源网络响应到一个网页。

First Make sure these resources are served with a correct " Content-Type ", ie, for JSON MIME type - " text/json ", " application/json ", HTML MIME type - " text/html ".首先确保这些资源使用正确的“ Content-Type ”,即对于 JSON MIME 类型 - “ text/json ”,“ application/json ”,HTML MIME 类型 - “ text/html ”。

Second: set mode to cors ie, mode:cors第二:将模式设置为 cors ie, mode:cors

The fetch would look something like this提取看起来像这样

 fetch("https://example.com/api/request", {
            method: 'POST',
            body: JSON.stringify(data),
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
                "Accept": 'application/json',
            }
        })
    .then((data) => data.json())
    .then((resp) => console.log(resp))
    .catch((err) => console.log(err))

references: https://chromium.googlesource.com/chromium/src/+/master/services/network/cross_origin_read_blocking_explainer.md参考资料: https : //chromium.googlesource.com/chromium/src/+/master/services/network/cross_origin_read_blocking_explainer.md

https://www.chromium.org/Home/chromium-security/corb-for-developers https://www.chromium.org/Home/chromium-security/corb-for-developers

You can not call third Party API directly from the client-side(frontend) of Your code. 您不能直接从代码的客户端(前端)调用第三方API。 for calling that you need to make changes in Server But You can not do. 用于调用,您需要在Server中进行更改,但是您不能这样做。 In the browser, You will get a normal response But from Js code, You will not get response. 在浏览器中,您将获得正常响应,但是从Js代码中,您将不会获得响应。 Try this Link Go here 试试这个链接去这里

I have a similar problem.我有一个类似的问题。 My case is because the contentType of server response is application/json, rather than text/javascript.我的情况是因为服务器响应的 contentType 是 application/json,而不是 text/javascript。

So, I solve it from my server (spring mvc):所以,我从我的服务器(spring mvc)解决它:

// http://127.0.0.1:8080/jsonp/test?callback=json_123456
    @GetMapping(value = "/test")
    public void testJsonp(HttpServletRequest httpServletRequest,
                          HttpServletResponse httpServletResponse,
                          @RequestParam(value = "callback", required = false) String callback) throws IOException {
        JSONObject json = new JSONObject();
        json.put("a", 1);
        json.put("b", "test");
        String dataString = json.toJSONString();

        if (StringUtils.isBlank(callback)) {
            httpServletResponse.setContentType("application/json; charset=UTF-8");
            httpServletResponse.getWriter().print(dataString);
        } else {
            // important: contentType must be text/javascript
            httpServletResponse.setContentType("text/javascript; charset=UTF-8");
            dataString = callback + "(" + dataString + ")";
            httpServletResponse.getWriter().print(dataString);
        }
    }

If you do it in safari it takes no time, Just enable the developer menu from Preferences >> Privacy, and deselect "Disable Cross-Origin Restrictions" from the develop menu. 如果您在野生动物园中进行操作不花时间,只需在“偏好设置”>“隐私”中启用开发人员菜单,然后从开发菜单中取消选择“禁用跨域限制”。 If you want local only, then you only need to enable the developer menu, and select "Disable local file restrictions" from the develop menu. 如果只需要本地文件,则只需启用开发人员菜单,然后从开发菜单中选择“禁用本地文件限制”。

and in Chrome for OSX open Terminal and run: 并在Chrome for OSX中打开终端并运行:

$ open -a Google\ Chrome --args --disable-web-security --user-data-dir

--user-data-dir required on Chrome 49+ on OSX --OSX上的Chrome 49+需要--user-data-dir

For Linux run: 对于Linux运行:

$ google-chrome --disable-web-security

Also if you're trying to access local files for dev purposes like AJAX or JSON, you can use this flag too. 另外,如果您尝试出于开发目的(例如AJAX或JSON)访问本地文件,也可以使用此标志。

-–allow-file-access-from-files

For Windows go into the command prompt and go into the folder where Chrome.exe is and type 对于Windows,请进入命令提示符并进入Chrome.exe所在的文件夹,然后键入

chrome.exe --disable-web-security

That should disable the same origin policy and allow you to access local files. 那应该禁用相同的原始策略,并允许您访问本地文件。

I had the same problem with my Chrome extension.我的 Chrome 扩展程序也有同样的问题。 When I tried to add to my manifest "content_scripts" option this part:当我尝试将这部分添加到我的清单“content_scripts”选项时:

//{
    //  "matches": [ "<all_urls>" ],
    //  "css": [ "myStyles.css" ],
    //  "js": [ "test.js" ]
    //}

And I remove the other part from my manifest "permissons":我从我的清单“许可”中删除了另一部分:

"https://*/"

Only when I delete it CORB on one of my XHR reqest disappare.只有当我在我的 XHR 请求之一中删除它时,CORB 才会消失。

Worst of all that there are few XHR reqest in my code and only one of them start to get CORB error (why CORB do not appare on other XHR I do not know; why manifest changes coused this error I do not know).最糟糕的是,我的代码中几乎没有 XHR 请求,只有一个开始出现 CORB 错误(为什么我不知道其他 XHR 上没有出现 CORB;为什么清单更改会导致这个错误,我不知道)。 That's why I inspected the entire code again and again by few hours and lost a lot of time.这就是为什么我花了几个小时一次又一次地检查整个代码并浪费了很多时间。

I encountered this problem because the format of the jsonp response from the server is wrong.我遇到这个问题是因为服务器的jsonp响应格式不对。 The incorrect response is as follows.错误的回答如下。

callback(["apple", "peach"])

The problem is, the object inside callback should be a correct json object, instead of a json array.问题是, callback中的对象应该是正确的 json 对象,而不是 json 数组。 So I modified some server code and changed its format:所以我修改了一些服务器代码并改变了它的格式:

callback({"fruit": ["apple", "peach"]})

The browser happily accepted the response after the modification.浏览器愉快地接受了修改后的响应。

Try to install "Moesif CORS" extension if you are facing issue in google chrome.如果您在 google chrome 中遇到问题,请尝试安装“Moesif CORS”扩展程序。 As it is cross origin request, so chrome is not accepting a response even when the response status code is 200由于它是跨源请求,因此即使响应状态代码为 200,chrome 也不接受响应

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 CORB:JSFiddle 上的跨域读取阻塞 - CORB: Cross-Origin Read Blocking on JSFiddle 本地文件中的跨域读取阻塞 (CORB) - Cross-Origin Read Blocking (CORB) in a local file 使用MIME类型application / json的跨源读取阻止(CORB) - Cross-Origin Read Blocking (CORB) with MIME type application/json 自 2019 年 3 月 5 日起,跨域读取阻塞 (CORB) 阻止了跨域响应 - Cross-Origin Read Blocking (CORB) blocked cross-origin response since 5th March 2019 ajax发布请求-跨域读取阻止(CORB)阻止了跨源响应CORS - ajax post request - cross-Origin Read Blocking (CORB) blocked cross-origin response CORS 谷歌地图 api:跨源读取阻塞 (CORB) 阻止了跨源响应 - Google maps api: Cross-Origin Read Blocking (CORB) blocked cross-origin response 跨域读取阻塞 (CORB) 阻止了跨域响应 - Cross-Origin Read Blocking (CORB) blocked cross-origin response 如何在JS控制台中修复“跨域读取阻止(CORB)阻止跨源响应”? - How to fix “Cross-Origin Read Blocking (CORB) blocked cross-origin response” in the JS console? "如何解决跨域读取阻塞 (CORB) 阻止的跨域响应<URL>" - how to resolve Cross-Origin Read Blocking (CORB) blocked cross-origin response <URL> 跨域读取阻止 (corb) 阻止了 mime 类型 text/html 的跨域响应 - cross-origin read blocking (corb) blocked cross-origin response with mime type text/html
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM