2

I am getting the following error while making a CORS request. Interestingly this is working in safari but not in google chrome and firefox. I have been looking through everything but haven't found any solution on the web.

I am trying to send json to server but as far as I know I need to make it string before sending it to the server so I am using JSON.stringify but at the end I am expecting json result from the server.

This is what I am getting on the curl call. (I just tried that to see the headers)

HTTP/1.1 200 OK
Date: Tue, 18 Apr 2017 15:13:04 GMT
Server: Apache
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: POST, OPTIONS
Access-Control-Max-Age: 21600
Content-Length: 213
Content-Type: application/json

and this is what I am getting on network tab in chrome

network tab

and the last part my code

    function foo(api_key, url, query, pdata, callback) {
        var result = 'none';
        if (typeof pdata != "undefined"){
            var mydata = {"api_key": api_key, "query": query, "data": pdata };
        }
        else {
            var mydata = {"api_key": api_key, "query": query};
        }
        $.ajax({
               method : "POST",
               url : url,
               data: JSON.stringify(mydata),
               contentType: "application/json;charset=UTF-8",
               cache: false,
               dataType: "json",
               success : function(data) {
               console.log("API call is working successfully!")
               callback(data);
               result = data  
         },
         error: function( data, status, error ) { 
               console.log("API call failed!")
         }
     });
     return result;
    }

This is the error I am getting.

XMLHttpRequest cannot load https://my_url. Request header field   Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
api.js:29 API call failed!`

What should I do, change or add to make it work in chrome and firefox?

9
  • If your backend isn't picky about the request Content-Type header, you could always set it to text/plain which makes it a simple request and thus, avoids a pre-flight OPTIONS request
    – Phil
    Apr 18, 2017 at 5:50
  • Try updating your options with crossDomain: true. This should be automatic, but maybe that fails?
    – Koen.
    Apr 18, 2017 at 6:10
  • 1
    Probably useful for future references, but please include textual content instead of simply posting screenshots/images of your code.
    – Terry
    Apr 18, 2017 at 6:14
  • @Koen no, have you even read the documentation for that property?
    – Phil
    Apr 18, 2017 at 8:37
  • @Phil what are you trying to say?
    – Koen.
    Apr 18, 2017 at 9:24

3 Answers 3

5

Your ajax request seems to be correct but the problem is on server side. For every cors request browser send a preflight request. Only after preflight request gets validated through server side you can send cors ajax request.

So based on the type of your server you are using for preflight request you need to send proper response to browser.

Proper response means set appropriate headers on the preflight request's response and send it back to client i.e browser.

For curl request you don't need to do that, because curl request does not goes through preflight request validation on server side.

It's only needed in case of browser's due to security reasons.

An example could be like this -

    HttpResponse response = new HttpResponse(request.getProtocolVersion(), NO_CONTENT);
    HttpHeaders headers = response.headers();

    headers.set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    headers.set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    headers.set(CACHE_CONTROL, "max-age=31536000, public");
    headers.set(ACCESS_CONTROL_ALLOW_ORIGIN, request.headers().get("Origin"));
    headers.set(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    headers.set(ACCESS_CONTROL_MAX_AGE, "31536000");
    headers.set(ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, OPTIONS");
    headers.set(ACCESS_CONTROL_ALLOW_HEADERS, request.headers().get("Access-Control-Request-Headers"));
    headers.set(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    send(response);

This is just an example but how you will do it on your side totally depends on your server side and server framework which you are using.

1
  • I realized that when I compare the response headers in safari and chrome. Content Type is coming as application/json in safari (as expected ) but in chrome content type is coming as text/html; charset=utf-8 so so you have any idea how to prevent chrome doing this?
    – hma
    Apr 18, 2017 at 19:13
0

Actually your preflight request is getting failed, as you are setting content-type but, no Content-Type header is present on response.

So, either don't set content-type to json instead use text/plain, form-data to bypass preflight request and directly send the ajax request to cross-domain server.

Or set Access-Control-Allow-Headers:Content-Type header on server.

To set header on apache

Header set Access-Control-Allow-Headers "Content-Type"

will work.

enter image description here

6
  • when I made API call through curl, I am seeing Access-Control-Allow-Headers: Content-Type in the response. So that means it have been already set toAccess-Control-Allow-Headers: Content-Type right ?
    – hma
    Apr 18, 2017 at 13:12
  • Yes .. if its their in response. It will be their in request only .. if not set at server ..IN the image uploaded by you .. the header is in request only .. not present in response. Apr 18, 2017 at 18:14
  • it is a flask project and I checked the server side and the options has been already set to response.headers.add("Access-Control-Allow-Origin", "*") response.headers.add("Access-Control-Allow-Headers", "Content-Type") but I am still getting Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
    – hma
    Apr 18, 2017 at 18:52
  • I realized that when I compare the response headers in safari and chrome. Content Type is coming as application/json in safari (as expected ) but in chrome content type is coming as text/html; charset=utf-8 so so you have any idea how to prevent chrome doing this?
    – hma
    Apr 18, 2017 at 19:13
  • Did you set the response type externally to application/json from flesk ? Apr 19, 2017 at 5:02
0

Problem is solved! everything on client side is correct

started to use CORS lib on the server

from flask_cors import CORS 

and as @WitVault says configuring server with these settings solved my problem!

cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.