Feirell
Feirell

Reputation: 799

CORS access blocking

I might need some help here.

I was trying to establish a connection with XMLHttpRequest from JavaScript to a PHP Script on another origin.

First thing I noticed was that I got a error from this request which told me that there were header missing. I searched a bit and found this documentation. I modified the header like this:

JS

//this.mozSystem = true;
this.open("POST", url, true);
this.setRequestHeader("Content-type", "application/json");
this.setRequestHeader("ADDON-TO-SERVER", "");
this.setRequestHeader("Content-length", massage.length);
this.setRequestHeader("Connection", "close");

PHP

header("Content-type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Request-Method: POST");
header("Access-Control-Allow-Headers: ADDON-TO-SERVER,Content-type");

And it works ... but I am not sure why in

header("Access-Control-Allow-Headers: ADDON-TO-SERVER,Content-type");

Content-type is needed.

Mozilla told me to add this one, but I though that it would just need one custom header, and isn't Content-type a basic one ?

Could someone tell me why this is needed and tell me if I done everything like it is intended to.

Thanks for any help, Feirell

Upvotes: 1

Views: 125

Answers (1)

sideshowbarker
sideshowbarker

Reputation: 88275

As far as headers go in the context of CORS, a Content-type request header with the value of application/json is not considered a “basic one” (to borrow your wording).

In the context of CORS, a Content-type request header is only considered “basic” if its value is application/x-www-form-urlencoded, multipart/form-data, or text/plain.

So your browser will allow a Content-type: application/json request from your Web application to work as expected only if the server you are sending that request to explicitly indicates that it’s OK with receiving such requests. And the way a server does that is by responding with a Access-Control-Allow-Headersheader that contains Content-type.

The rationale for your browser enforcing that restriction is that unless a server explicitly indicates is it OK with certain kinds of cross-origin requests, CORS is not intended to allow Web applications to do any kind of programmatic cross-origin requests that do anything more than what a basic HTML form-element action have always been able to do cross-origin.

And so since before CORS came along, HTML page have always been restricted just to sending application/x-www-form-urlencoded, multipart/form-data, or text/plain requests cross-origin, that’s what the basic CORS behavior is restricted to unless the server opts-in for more.

Upvotes: 1

Related Questions