Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PouchDB authentication triggering CORS preflight request

The following code (using the PouchDB Authentication plugin) fails because it triggers the browser to send a CORS preflight request, and CouchDB does not support the OPTIONS HTTP method.

var db = new PouchDB("http://localhost:5984/mydb");
db.login('username', 'password');
// assume the database URL and login info are valid

Here is the error (in Chrome). Note that this issue also occurs in Edge, but not in Firefox:

XMLHttpRequest cannot load http://localhost:5984/_session. Response for preflight has invalid HTTP status code 405

And here are the headers that Chrome is sending for the request (they are not significantly different in Firefox):

POST /_session HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 25
Accept: application/json
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:8080/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,es-419;q=0.6,es;q=0.4

I have already enabled CORS via the add-cors-to-couchdb Node script. Things I have tried:

  • Manually adding OPTIONS as a method under [cors] in my local.ini
  • Passing { ajax: { content_type: "text/plain" } } as the third argument to login

So, my question is:

  • How can I prevent the preflight request from being triggered? Looking at the MDN documentation, it doesn't seem necessary.
  • If the previous is not possible, how can I set my CouchDB server up to respond to preflight requests?
like image 510
rvighne Avatar asked Aug 09 '16 20:08

rvighne


1 Answers

Hitting this same issue. Seems Chrome has recently started being a little more aggressive about sending the OPTIONS preflight. A partial work around was to specify a specific origin in the CORS header instead of '*', so

curl -X PUT $HOST/_config/cors/origins -d '"localhost:8080"'

or similar.

I still am getting the preflight error, but now PouchDB successfully authenticates, so I can just ignore the error. I think the fix is to get CouchDB to respond to OPTIONS on the _session url.

Edit, more info here https://github.com/nolanlawson/pouchdb-authentication/issues/111

like image 79
Jeff Barnes Avatar answered Oct 19 '22 19:10

Jeff Barnes