POST方法的CORS设置似乎不起作用

时间:2016-11-21 02:18:01

标签: nginx cors

我正在尝试在我的后端使用一些javascript访问API,我已经将nginx设置为下方,官方网站上显示的那个,GET工作正常但是POST给了我以下错误。

XMLHttpRequest cannot load http://xxxxxxx/oauth/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxxxxxxx' is therefore not allowed access. The response had HTTP status code 401.

nginx.conf

   server {
        listen 80;
        server_name foo.com;
        root /var/bar/public;
        passenger_enabled on;

        location / {

                if ($request_method = 'OPTIONS') {
                        add_header 'Access-Control-Allow-Origin' '*';
                        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                        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';
                }
                if ($request_method = 'GET') {
                        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';
                }
        }
   }

更新:现在我已经在后端框架中添加了标题,在这种情况下是rails,并且作为解决它的工作正常,不是特别高兴,但我可以将资源放在别处。

对于任何感兴趣的人,代码都是下面的。

applicaiton_controller.rb

  before_action :custom_header


      def custom_header
        response.headers['Access-Control-Allow-Origin'] = '*'
      end

0 个答案:

没有答案