Cross-Origin Read Blocking (CORB)

JavascriptJqueryAjaxCorsCross Origin-Read-Blocking

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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.

Solution 6 - Javascript

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

Solution 7 - Javascript

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.

Solution 8 - Javascript

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

Solution 9 - Javascript

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.

Solution 10 - Javascript

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!

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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.

Solution 14 - Javascript

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.

Solution 15 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJigneshView Question on Stackoverflow
Solution 1 - JavascriptQuentinView Answer on Stackoverflow
Solution 2 - JavascriptAlexView Answer on Stackoverflow
Solution 3 - JavascriptJestinView Answer on Stackoverflow
Solution 4 - JavascriptShubham VermaView Answer on Stackoverflow
Solution 5 - JavascriptColin YoungView Answer on Stackoverflow
Solution 6 - JavascriptpmirandaView Answer on Stackoverflow
Solution 7 - JavascriptstepperView Answer on Stackoverflow
Solution 8 - JavascriptClaView Answer on Stackoverflow
Solution 9 - JavascriptSimon ThumView Answer on Stackoverflow
Solution 10 - JavascriptfluminisView Answer on Stackoverflow
Solution 11 - JavascriptlifetimeLearner007View Answer on Stackoverflow
Solution 12 - JavascriptlearnerView Answer on Stackoverflow
Solution 13 - JavascriptОлег ХитреньView Answer on Stackoverflow
Solution 14 - JavascriptSeareneView Answer on Stackoverflow
Solution 15 - JavascriptMadhurish GuptaView Answer on Stackoverflow