yanatan16 / nanoajax

An ajax library you need a microscope to see
MIT License
247 stars 42 forks source link

X-Requested-With breaks API call #19

Closed loup-brun closed 7 years ago

loup-brun commented 7 years ago

Hi,

I get an error message when attempting to make a POST cross-origin request to my API (it has to do with CORS preflight). Removing the X-Requested-With header enables me to make my requests. Is there a way I can do this in configuration (i.e. without altering the source code of nanoajax)?

yanatan16 commented 7 years ago

@loup-brun Sorry, I didn't see this until now...

Try

ajax({url: 'blahblah', headers: {'X-Requested-With': ' '}})

This will probably work because ' ' is truthy in javascript but should be ingored by your web server.

loup-brun commented 7 years ago

This is not an issue with the webserver, it's the browser not allowing the request to be done cross-domain – i.e., it is never sent with X-Requested-With.

If I remove X-Requested-With from nanoajax, the request works fine.

What's the point of this header?

yanatan16 commented 7 years ago

The point of this header is to prevent CSRF attacks on your page by forcing the requesting server to explicitly allow ajax via CORS. When the header is added, the browser does a pre-flight request (a HEAD usually) to see what the CORS rules are. The server response must allow the X-Requested-With header.

See http://stackoverflow.com/questions/17478731/whats-the-point-of-the-x-requested-with-header and https://remysharp.com/2011/04/21/getting-cors-working.

Likely your issue lies on your CORS configuration on your server.

loup-brun commented 7 years ago

Good! Thank you, resolved ;)