Подтвердить что ты не робот

Как включить CORS в прокси-сервер Nginx?

Как мой заголовок, вот файл конфигурации, расположенный в conf.d/api-server.conf

server {
  listen 80;
  server_name api.localhost;

  location / {
    add_header 'Access-Control-Allow-Origin' 'http://api.localhost';
    add_header 'Access-Control-Allow_Credentials' 'true';
    add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

    if ($request_method = 'OPTIONS') {
      add_header 'Access-Control-Max-Age' 1728000;
      add_header 'Content-Type' 'text/plain charset=UTF-8';
      add_header 'Content-Length' 0;
      return 204;
    }

    proxy_redirect off;
    proxy_set_header host $host;
    proxy_set_header X-real-ip $remote_addr;
    proxy_set_header X-forward-for $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:3000;
  }
}

Файл nginx.conf остается таким же, как по умолчанию.

После того, как я отправил запрос на api.localhost(api.localhost/admin/login), я все еще получаю ошибку 405:

XMLHttpRequest cannot load http://api.localhost/admin/login. Response 
to preflight request doesn't pass access control check: No 'Access-
Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://admin.localhost:3000' is therefore not allowed access. 
The response had HTTP status code 405.

That is the response from server That's the request looks like

4b9b3361

Ответ 1

Проблема заключается в том, что ваше условие if не отправляет заголовки в родительский элемент в /. Если вы проверите заголовки ответов перед полетом, это будет

HTTP/1.1 204 No Content
Server: nginx/1.13.3
Date: Fri, 01 Sep 2017 05:24:04 GMT
Connection: keep-alive
Access-Control-Max-Age: 1728000
Content-Type: text/plain charset=UTF-8
Content-Length: 0

И это ничего не дает. Так что два возможных исправления для вас. Скопируйте add_header внутрь, если блок также

server {
  listen 80;
  server_name api.localhost;

  location / {
    add_header 'Access-Control-Allow-Origin' 'http://api.localhost';
    add_header 'Access-Control-Allow_Credentials' 'true';
    add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

    if ($request_method = 'OPTIONS') {
      add_header 'Access-Control-Allow-Origin' 'http://api.localhost';
      add_header 'Access-Control-Allow_Credentials' 'true';
      add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
      add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';
      add_header 'Access-Control-Max-Age' 1728000;
      add_header 'Content-Type' 'text/plain charset=UTF-8';
      add_header 'Content-Length' 0;
      return 204;
    }

    proxy_redirect off;
    proxy_set_header host $host;
    proxy_set_header X-real-ip $remote_addr;
    proxy_set_header X-forward-for $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:3000;
  }
}

Или вы можете переместить его за пределы блока местоположения, поэтому каждый запрос имеет ответ

server {
   listen 80;
   server_name api.localhost;

 add_header 'Access-Control-Allow-Origin' 'http://api.localhost';
 add_header 'Access-Control-Allow_Credentials' 'true';
 add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
 add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

  location / {

    if ($request_method = 'OPTIONS') {
      add_header 'Access-Control-Max-Age' 1728000;
      add_header 'Content-Type' 'text/plain charset=UTF-8';
      add_header 'Content-Length' 0;
      return 204;
    }

    proxy_redirect off;
    proxy_set_header host $host;
    proxy_set_header X-real-ip $remote_addr;
    proxy_set_header X-forward-for $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:3000;
  }
}

Если вы хотите разрешить определенные местоположения в вашей конфигурации для CORS. например /api, тогда вы должны создать шаблон conf с заголовками

 add_header 'Access-Control-Allow-Origin' 'http://api.localhost';
 add_header 'Access-Control-Allow_Credentials' 'true';
 add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
 add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

а затем используйте

include conf.d/corsheaders.conf;

в блоке OPTIONS и /api. Таким образом, CORS разрешено только для /api. Если вам не важно, какое место для CORS, то вы можете использовать второй подход для перемещения заголовков ядра к серверному блоку.

Ответ 2

Я попробовал комментарий от, и он не работал для меня со следующей ошибкой:

The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request credentials mode is 'include'

пока я не изменил эту строку:

add_header 'Access-Control-Allow_Credentials' 'true';

чтобы:

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