Javascript 跨源读取阻塞 (CORB)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50873764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:42:14  来源:igfitidea点击:

Cross-Origin Read Blocking (CORB)

javascriptjqueryajaxcorscross-origin-read-blocking

提问by Jignesh

I have called third party API using Jquery AJAX. I am getting following error in console:

我使用 Jquery AJAX 调用了第三方 API。我在控制台中收到以下错误:

Cross-Origin Read Blocking (CORB) blocked cross-origin response MY URLwith MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768for more details.

跨域读取阻止 (CORB) 阻止了具有 MIME 类型 application/json 的跨域响应MY URL。有关更多详细信息,请参阅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.

请帮帮我。

回答by Quentin

 dataType:'jsonp',
 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. (If the browser didtry to treat the JSON as JSONP then it would, at best, fail).

浏览器拒绝尝试将 JSON 视为 JSONP,因为这会带来安全风险。(如果浏览器确实尝试将 JSON 视为 JSONP,那么它最多会失败)。

See this questionfor more details on what JSONP is. Note that is a nasty hack to work around the Same Origin Policy that was used before CORS was available. CORS is a much cleaner, safer, and more powerful solution to the problem.

有关什么是 JSONP 的更多详细信息,请参阅此问题。请注意,在 CORS 可用之前使用的同源策略是一个令人讨厌的技巧。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 questionfor an in-depth guide.

有关深入指南,请参阅此问题



Now a few notes about your code:

现在对您的代码进行一些说明:

contentType: 'application/json',
contentType: 'application/json',
  • This is ignored when you use JSONP
  • You are making a GET request. 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.
  • 当您使用 JSONP 时,这将被忽略
  • 您正在发出 GET 请求。没有请求正文来描述类型。
  • 这将使跨域请求变得不简单,这意味着除了基本的 CORS 权限外,您还需要处理预检。

Remove that.

去掉那个。

 dataType:'jsonp',
 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',
responseType:'application/json',

This is not an option supported by jQuery.ajax. Remove this.

这不是 jQuery.ajax 支持的选项。去掉这个。

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',
  },
  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 权限外,您还需要处理预检。

回答by Alex

In most cases, the blocked response should not affect the web page's behavior and the CORB error message can be safely ignored. 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 (e.g., a HTML document such as a 404 error page being delivered to an tag).

在大多数情况下,被阻止的响应不应影响网页的行为,并且可以安全地忽略 CORB 错误消息。例如,当被阻止响应的主体已经为空时,或者当响应将被传递到无法处理它的上下文(例如,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. I was receiving CORS because the chrome had saved the PORT number on the cache, The server would just accept localhost:3010and I was doing localhost:3002, because of the cache.

我必须清理浏览器的缓存,我正在阅读此链接,如果请求得到空响应,我们会收到此警告错误。我的请求得到了一些 CORS,因此该请求的响应为空,我所要做的就是清除浏览器的缓存,然后 CORS 就消失了。我收到 CORS 是因为 chrome 已将端口号保存在缓存中,由于缓存,服务器只会接受localhost:3010而我正在这样做localhost:3002

回答by Jestin

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); 

回答by Shubham Verma

You have to add CORS on the server side:

您必须在服务器端添加 CORS:

If you are using nodeJSthen:

如果您使用的是nodeJS,则:

First you need to installcorsby using below command :

首先,您需要cors使用以下命令进行安装

npm install cors --save

Now add the following codeto 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);

回答by Colin Young

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
  • Open the AutoRespondertab
  • Click Add Ruleand edit the rule to:
    • Method:OPTIONS server url here, e.g. Method:OPTIONS http://localhost
    • *CORSPreflightAllow
  • Check Unmatched requests passthrough
  • Check Enable Rules
  • 在 Fiddler 中选择问题请求
  • 打开AutoResponder选项卡
  • 单击Add Rule并将规则编辑为:
    • 方法:此处的OPTIONS服务器 url,例如Method:OPTIONS http://localhost
    • *CORSPreflightAllow
  • 查看 Unmatched requests passthrough
  • 查看 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
  2. Check that any agreements you have with the third-party API provider allow you to do this
  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. 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.
  1. 显然,这只是开发/测试的解决方案,其中修改 API 服务是不可能/不切实际的
  2. 检查您与第三方 API 提供商达成的任何协议是否允许您执行此操作
  3. 正如其他人所指出的,这是 CORS 工作方式的一部分,最终需要在 API 服务器上设置标头。如果您控制该服务器,则可以自己设置标头。在这种情况下,由于它是第三方服务,我只能假设他们有某种机制,通过该机制您可以向他们提供原始站点的 URL,他们将相应地更新他们的服务以使用正确的标头进行响应。

回答by pmiranda

If you are working on localhost, try this, this one the only extension and method that worked for me (Angular, only javascript, no php)

如果你在 localhost 上工作,试试这个,这是唯一对我有用的扩展和方法(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

回答by stepper

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 问题上,这为我解决了这个问题。

回答by Cla

have you tried changing the dataTypein your ajax request from jsonpto json? that fixed it in my case.

您是否尝试将dataTypeajax 请求中的更改jsonpjson?在我的情况下修复了它。

回答by fluminis

It seems that this warning occured when sending an empty response with a 200.

似乎在发送带有 200 的空响应时发生了此警告。

This configuration in my .htaccessdisplay 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!

解决问题!

回答by Simon Thum

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. 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. Also, the body of a CORS preflight is not accessible, so there is no negative consequence just an irritating warning.

在这种情况下,有一个边缘情况值得一提:Chrome(至少某些版本) 使用为 CORB 设置的算法检查 CORS 预检。IMO,这有点愚蠢,因为预检似乎不会影响 CORB 威胁模型,而且 CORB 似乎被设计为与 CORS 正交。此外,无法访问 CORS 预检的正文,因此没有负面后果,只是一个令人讨厌的警告。

Anyway, check that your CORS preflight responses (OPTIONS method responses) don't have a body (204). An empty 200 with content type application/octet-stream and length zero worked well here too.

无论如何,请检查您的 CORS 预检响应(OPTIONS 方法响应)是否没有正文 (204)。内容类型为 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 响应来确认您是否遇到了这种情况。