overcomming CORS - hogehoge666/syno_moments_slider GitHub Wiki


Conclusion

  • if your production environment doesn't require CORS, use a reverse proxy server
  • don't waste your time trying to make CORS work

Errors sending/receiving data

Problem

  • The Browser doesn't allow cross-origin if the server you are making a request to doesn't send Access-Control-Allow-XXX headers.
  • You see a CORS error in the development tool

Solution

  • Modify server config to send Access-Control-Allow-XXX headers.
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods "POST, GET, OPTIONS";
    add_header Access-Control-Allow-Headers "Origin, Authorization, Accept";
    add_header Access-Control-Allow-Credentials true;

Limitations

  • Web Application may overwrite response header deletes Access-Control-Allow-XXX headers.
  • Cookies are not sent

Errors sending Cookies

Problem

  • The browsers and APIs don't send cookies in cross-origin communication by default

Solution

  • Configure your API to include cookies
  • The following example illustrates how you can configure Fetch API to include cookies in a request
credentials: 'include'
  • Modify server config not to send * in Access-Control-Allow-Origin
    add_header Access-Control-Allow-Origin $http_origin always;
  • Modify server config to send SameSite=None,Secure
  • This is especially important for the Chrome browser. SameSite=None,Secure
  proxy_cookie_path / "/; secure; SameSite=none";
  • 'Secure' means the browser only sends cookies in the HTTPS session
  • Modify server config and your app to support HTTPS

Recommendation

  • making CORS work is hard
  • if your production environment requires CORS, there are libraries/frameworks that do the heavy lifting for you
  • use them as they are easier and safer
  • if you want to make CORS work just for your local development, simply use a reverse proxy
    • don't waste your time working on things you don't use in production
  • Here is an example of a reverse proxy configuration
    • name it http.XXX.conf and place it in /etc/nginx/conf.d
server {
  listen  15000;

  location / {
    root  /usr/share/nginx/html/synoMomentsSlider;
    index  index.html index.htm;
  }

  location /webapi {
    proxy_pass  http://192.168.11.2:5000;
  }
}