Recommended solution for AJAX, CORS, Chrome & HTTP error codes (401,403,404,500)

后端 未结 3 490
悲哀的现实
悲哀的现实 2020-12-25 08:29

Background

(If you are familiar with CORS, you might skip to the Question at the end)

CORS [1] is a solution to a

相关标签:
3条回答
  • 2020-12-25 08:44

    Now after much fiddling, I've managed to make it work. blush

    There seems to be an awful lot of voodoo which makes up the exact scenario that ensures CORS will work in each browser, however having traced back numerous issues like:

    • Nginx, by default, only uses HTTP/1.0 in it's reverse proxy by default
    • Tomcat silently ignores duplicate init-param declaration with the same key, but jetty combines them (so CORS filter was off in server but on in dev-laptop), and nginx was overwriting some headers.

    Having stumbled upon what seemed to be a complete no-go, I ended up writing a CORS 4xx->200 wrapper as a jquery plugin,in an attempt to solve the issue. Debugging that plugin led me to my eventual fix.

    0 讨论(0)
  • 2020-12-25 08:52

    I spend a couple of hours today hunting for the answer to this, while developing a web app on Chrome. Some others have written fairly detailed analyses of this situation.

    There were two potential issues:

    1. It could be that Chrome was doing a preflight and was getting a non-200 or a non-CORS response in response

      • Specs about Preflights (When they Occur)
    2. For some reason my non-200 (error) status codes were not getting the headers attached. As I found out in this post, this second reason was the issue. Essentially, NGINX only adds headers on successful responses by default. To get my error responses through CORS, it sufficed to change

    add_header 'Access-Control-Allow-Origin' '*';
    

    to

    add_header 'Access-Control-Allow-Origin' '*' always;
    

    As the article notes, you may also have to add always to 'Access-Control-Allow-Credentials' and 'Access-Control-Allow-Headers'. After doing this, all error codes also went through without CORS issues. It may be that the program you are using for API serving does the same. Hope this helps and saves someone some time!

    0 讨论(0)
  • 2020-12-25 08:58

    Just ran into this issue. Setting the HTTP headers for the 401 response did the trick for me. The library I was using wasn't doing this properly without some customization. e.g.:

      self.headers["Access-Control-Max-Age"] = '1728000'
      self.headers["Access-Control-Allow-Origin"] = "http://localhost:3001"
      self.headers["Access-Control-Allow-Methods"] = "ANY"
      self.headers["Access-Control-Allow-Credentials"] = 'true'
    
    0 讨论(0)
提交回复
热议问题