CORB (Cross-Origin Read Blocking)
Jquery AJAX를 사용하여 타사 API를 호출했습니다. 콘솔에서 다음 오류가 발생합니다.
CORB (Cross-Origin Read Blocking) 가 MIME 유형 application / json을 사용하여 교차 출처 응답 내 URL 을 차단했습니다 . 자세한 내용은 https://www.chromestatus.com/feature/5629709824032768 을 참조하세요.
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....=================");
}
});
Fiddler를 체크인했을 때 Ajax 성공 방법이 아닌 응답으로 데이터를 얻었습니다.
제발 도와주세요.
dataType:'jsonp',
JSONP 요청을하고 있지만 서버가 JSON으로 응답하고 있습니다.
브라우저는 보안 위험이 있으므로 JSON을 JSONP로 취급하는 것을 거부합니다. (브라우저 가 JSON을 JSONP로 처리하려고하면 기껏해야 실패합니다).
JSONP가 무엇인지에 대한 자세한 내용 은 이 질문 을 참조하십시오. CORS가 사용 가능하기 전에 사용 된 동일한 출처 정책을 해결하기위한 불쾌한 해킹입니다. CORS는 문제에 대한 훨씬 깨끗하고 안전하며 강력한 솔루션입니다.
교차 출처 요청을 시도하고 있으며 충돌하는 명령 더미 하나에 생각할 수있는 모든 것을 던지고있는 것 같습니다.
동일한 출처 정책이 어떻게 작동하는지 이해해야합니다.
자세한 가이드는 이 질문 을 참조하세요 .
이제 코드에 대한 몇 가지 참고 사항 :
contentType: 'application/json',
- JSONP를 사용할 때 무시됩니다.
- GET 요청을하고 있습니다. 유형을 설명하는 요청 본문이 없습니다.
- 이렇게하면 원본 간 요청이 단순하지 않게됩니다. 즉, 기본 CORS 권한뿐 아니라 사전 비행도 처리해야합니다.
그것을 제거하십시오.
dataType:'jsonp',
- The server is not responding with JSONP.
Remove this. (You could make the server respond with JSONP instead, but CORS is better).
responseType:'application/json',
This is not an option supported by jQuery.ajax. Remove this.
xhrFields: { withCredentials: false },
This is the default. Unless you are setting it to true with ajaxSetup, remove this.
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.
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).
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:3010
and I was doing localhost:3002
, because of the cache.
Return response with header 'Access-Control-Allow-Origin:*' Check below code for the Php server response.
<?php header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
echo json_encode($phparray);
You have to add CORS on the server side:
If you are using nodeJS then:
First you need to install cors
by using below command :
npm install cors --save
Now add the following code to your app starting file like ( 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:
- Select the problem request in Fiddler
- Open the
AutoResponder
tab - Click
Add Rule
and edit the rule to:- Method:OPTIONS server url here, e.g.
Method:OPTIONS http://localhost
*CORSPreflightAllow
- Method:OPTIONS server url here, e.g.
- Check
Unmatched requests passthrough
- Check
Enable Rules
A couple notes:
- Obviously this is only a solution for development/testing where it isn't possible/practical to modify the API service
- Check that any agreements you have with the third-party API provider allow you to do this
- 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.
have you tried changing the dataType
in your ajax request from jsonp
to json
? that fixed it in my case.
If you are working on localhost, try this, this one the only extension and method that worked for me (Angular, only javascript, no php)
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.
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.
You can confirm if this is the case you are hitting by counting CORB warnings vs. OPTIONS responses with a message body.
It seems that this warning occured when sending an empty response with a 200.
This configuration in my .htaccess
display the warning on 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
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.
First Make sure these resources are served with a correct "Content-Type
", i.e, for JSON MIME type - "text/json
", "application/json
", HTML MIME type - "text/html
".
Second: set mode to cors i.e, 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))
https://www.chromium.org/Home/chromium-security/corb-for-developers
I had the same problem with my Chrome extension. When I tried to add to my manifest "content_scripts" option this part:
//{
// "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.
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). That's why I inspected the entire code again and again by few hours and lost a lot of time.
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:
$ open -a Google\ Chrome --args --disable-web-security --user-data-dir
--user-data-dir required on Chrome 49+ on OSX
For Linux run:
$ 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.
-–allow-file-access-from-files
For Windows go into the command prompt and go into the folder where Chrome.exe is and type
chrome.exe --disable-web-security
That should disable the same origin policy and allow you to access local files.
I encountered this problem because the format of the jsonp response from the server is wrong. 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. 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. As it is cross origin request, so chrome is not accepting a response even when the response status code is 200
참고URL : https://stackoverflow.com/questions/50873764/cross-origin-read-blocking-corb
'program story' 카테고리의 다른 글
SilverStripe PHP Forms-FieldGroup 내에 SelectionGroup을 중첩하면 관련 SelectionGroup_Items의 Radio Box 중 하나가 표시되지 않습니다. (0) | 2020.08.24 |
---|---|
iOS 5에서 빠르고 효율적인 핵심 데이터 가져 오기 구현 (0) | 2020.08.24 |
0 기반 월 번호 매기기 (0) | 2020.08.24 |
Android Marshmallow의 서비스에서 권한을 요청하는 방법 (0) | 2020.08.24 |
RESTful API의 API 키 vs HTTP 인증 vs OAuth (0) | 2020.08.24 |