77

I'm trying to make CORS request POST from domain.example to a.domain.example.

My JavaScript looks like this

$('#fileupload').fileupload({
  xhrFields: {
    withCredentials: true
  },
  dataType: 'json',
  url: $('#fileupload').data('path'),
  singleFileUploads: true,
  add: function(e, data){
    data.submit();
  }
});

At first I see the OPTIONS route being called like so:

Request URL: https://a.domain.example/some/route
Request Method:OPTIONS
Status Code:200 OK

OPTIONS REQUEST:

Access-Control-Request-Headers:origin, content-type, accept
Access-Control-Request-Method:POST
Host:a.domain.example
Origin:http://domain.example:3000
Referer:http://domain.example:3000/home

OPTIONS RESPONSE

Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:POST
Access-Control-Allow-Origin:http://domain.example:3000
Connection:keep-alive
Content-Length:0
Content-Type:text/html;charset=utf-8

That request comes back with a 200 like stated. On my server, I have the same route with POST method and this is what I get in return after the OPTIONS

Request URL:https://a.domain.example/some/route

POST REQUEST

Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryjwr5Pk7WBcfzMdbO
Origin:http://domain.example:3000
Referer:http://domain.example:3000/home

and the POST request gets canceled/fails.

My question is, do I need to have the access-control-allow-origin on the POST controller as well?

I have a cookie for authorization that has domain .domain.example that cookie got sent across once in a request and it's not being sent now. Any idea why that would happen?

1 Answer 1

94

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.example:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

3
  • 1
    Can the protocol be omitted? or can you add one with both http and https?
    – Michael
    Mar 1, 2017 at 12:04
  • protocol can't be omitted, you have to use domain, protocol, and port Oct 10, 2018 at 11:42
  • Access-Control-Allow-Origin: * is not allowing anymore. you have to add headers manually. Sep 20, 2020 at 10:21

Your Answer

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

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