F
F
frontendo2017-09-01 23:59:52
Nginx
frontendo, 2017-09-01 23:59:52

Why doesn't NGINX add headers on responses from nodejs other than 200?

ran into a problem. This is how I have nginx configured

server {  
  listen 80;
  server_name api.ru;
  root /home/user/ее/static;
  access_log off;
  error_log /var/log/nginx/sitename.ru.log error;

  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header Host $http_host;
  proxy_set_header X-NginX-Proxy true;

  location / {
    proxy_pass http://localhost:8080;
    proxy_redirect off;

    if ($request_method = 'OPTIONS') {
      add_header 'Access-Control-Allow-Origin' '*';
      add_header 'Access-Control-Allow-Credentials' 'true';
      add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
      add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
      add_header 'Access-Control-Max-Age' 1728000;
      add_header 'Content-Type' 'text/plain charset=UTF-8';
      add_header 'Content-Length' 0;
      return 204;
    }
    if ($request_method = 'POST') {
      add_header 'Access-Control-Allow-Origin' '*';
      add_header 'Access-Control-Allow-Credentials' 'true';
      add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
      add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
    }
  }
}

so, when node.js returns responses with status 200, then everything is fine and the indicated headers are added, but if I want to return, for example, 422, when the user entered incorrect data, then these headers are not added, as a result, fetch cannot resolve on the front promise and the app hangs

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lynn "Coffee Man", 2017-09-04
@frontendo

The add_header documentation says that by default headers are added only for 20x and 30x response codes.
To add headers always, you need to use the always flag .

add_header 'Access-Control-Allow-Credentials' 'true' always;

B
Boris Korobkov, 2017-09-02
@BorisKorobkov

Because if is evil doesn't work the way you think. Use map .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question