181

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

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

I have used following code for Ajax call :

$.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.

Please help me out.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Jignesh
  • 1,839
  • 2
  • 8
  • 5
  • 4
    It looks as though the API you're calling hasn't enabled the headers required to allow cross-domain calls from JS. You'll most likely need to make the call on the server instead. Are you sure the response is JSONP and not plain JSON? Also note that the headers you're adding in the request need to instead be placed in the *response* from the server. – Rory McCrossan Jun 15 '18 at 10:34
  • 4
    Have you solved this CORB error or warning? I'm experiencing the same with request module. – Sherwin Ablaña Dapito Aug 21 '18 at 10:18
  • 5
    @SherwinAblañaDapito if you are still looking for a solution, see [my answer](https://stackoverflow.com/a/52484747/173225) for development/test environments – Colin Young Sep 24 '18 at 17:48
  • 1
    **To demonstrate** how your JS can work correctly, you can start Chrome in an unsafe mode chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security But "Read Blocking (CORB) blocked cross-origin response" **must be fixed on the server side.** – Ruslan Novikov Sep 29 '18 at 10:01

15 Answers15

57
 dataType:'jsonp',

You are making a JSONP request, but the server is responding with JSON.

The browser is refusing to try to treat the JSON as JSONP because it would be a security risk. (If the browser did try to treat the JSON as JSONP then it would, at best, fail).

See this question for 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.


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
  • 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.

Remove that.

 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.
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
20

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.

Marcelo
  • 1,486
  • 13
  • 16
14

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); 
Jestin
  • 578
  • 5
  • 10
  • 3
    Your response just helped me SO MUCH!!! I simply cannot thank you enough. I will continue to research what the "Access Control Allow Origin" does so I understand the ramifications but I am just learning the basics of creating a PHP web service and this helped me like you wouldn't believe. THANK YOU!!! – Adam Laurie Jun 15 '19 at 22:52
  • This doesn't address the problem at all. It's a CORB error caused by sending a response with `Content-Type: application/json` in it. The OP's code must already be doing this. – Quentin Jun 24 '19 at 08:07
  • 1
    @Quentin, ??? Common sense states that as long as you have Allow Origin, the browser will allow the request regardless of any suspicious header/body. – Pacerier Jun 12 '20 at 14:00
  • @Pacerier — Common sense, and the CORB error message, says that if you try to execute a JSON file as if it was JavaScript, then it will fail. – Quentin Jun 23 '22 at 09:52
8

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);
Shubham Verma
  • 8,783
  • 6
  • 58
  • 79
  • 28
    If you need to add an extention to fix your problem, you are wrongly handling the request at the server-side. Just a note. – Alexander Falk Jul 23 '18 at 13:02
  • 3
    It's unfeasible to ask that my user base installs a weird Chrome extension. What about other browsers? – Izzy Rodriguez Jul 29 '18 at 16:43
  • 2
    While this answer doesn't solve the problem long-term, it was using this plugin that verified to my co-workers it was a CORS issue. So upvoted for that! – KoldBane Aug 29 '18 at 18:22
  • 1
    @IsraelRodriguez you are wrong, this is not a Chrome extension. This has to be installed on server side, because is the server who has to allow access. – Alonso Urbano Feb 01 '19 at 20:53
  • 2
    @VladimirNul the original answer was about a chrome extension. Shubham rewrote it. Check history please. – Izzy Rodriguez Feb 02 '19 at 07:51
  • 4
    There is some confusion here. The OP is referring to CORB and not CORS. – Not a machine Mar 08 '19 at 18:08
  • 2
    If you're going to fundamentally change your answer with an edit, you should consider creating a new answer. Especially if it's in response to comments – spicy.dll Jun 24 '19 at 14:51
3

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
  • Check Unmatched requests passthrough
  • Check 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.
Colin Young
  • 3,018
  • 1
  • 22
  • 46
3

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

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

pmiranda
  • 7,602
  • 14
  • 72
  • 155
3

In a Chrome extension, you can use

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

I was stuck on CORB issues, and this fixed it for me.

stepper
  • 239
  • 2
  • 3
  • 2
    "Starting from Chrome 72, if you need to modify responses before Cross Origin Read Blocking (CORB) can block the response, you need to specify 'extraHeaders' in opt_extraInfpSpec." from the webRequests doc – swisswiss Apr 05 '20 at 05:47
2

have you tried changing the dataType in your ajax request from jsonp to json? that fixed it in my case.

Cla
  • 303
  • 1
  • 3
  • 11
2

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.

Simon Thum
  • 576
  • 4
  • 15
1

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!

fluminis
  • 3,575
  • 4
  • 34
  • 47
0

I have a similar problem. My case is because the contentType of server response is application/json, rather than text/javascript.

So, I solve it from my server (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);
        }
    }

learner
  • 1,381
  • 1
  • 10
  • 16
-1

Response headers are generally set on the server. Set 'Access-Control-Allow-Headers' to 'Content-Type' on server side

  • 8
    I am using 3rd party API. So I can't do that. Please give me any client side solution. – Jignesh Jun 16 '18 at 16:25
  • 4
    Server decides what to allow and what not to. Only server has that access. Controlling response headers from client side is a security risk. The job of client side is to send proper request and then get whatever the response sent by the server. See this: https://stackoverflow.com/questions/17989951/setting-response-header-with-javascript – lifetimeLearner007 Jun 16 '18 at 16:35
  • 56
    This is CORB, not CORS. – Joaquin Brandan Aug 15 '18 at 17:48
  • 1
    I was looking for CORB help- this solved it- thank you!! – mydoglixu Dec 11 '21 at 16:51
-2

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.

  • There was some problem with headers on server side. I change my ASP.NET return value to: public async Task Get(string TM) Return value was a moment ago JSON (content type I guess "application/json") and now it is the other (may be "text/plain"). And it helps. Now I return manifest "permissions" to "https://*/" and it works. – Олег Хитрень Jul 07 '19 at 11:40
-4

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.

Searene
  • 25,920
  • 39
  • 129
  • 186
  • `callback(["apple", "peach"])` is perfectly valid JSONP, and worked fine when I tested it across origins. – Quentin Jun 24 '19 at 07:58
-4

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