在nginx服务器上使用Django API:出现Access-Control-Allow-Origin错误

时间:2019-06-30 01:57:11

标签: nginx cors

我们得到的错误是:

  

获取http://192.168.1.149:8000/api/product-title-by-isbn/9781640532632/   404(未找到)

     

在以下位置访问XMLHttpRequest   'http://192.168.1.149:8000/api/product-title-by-isbn/9781640532632/'   (重定向自   'http://192.168.1.149:8000/api/product-title-by-isbn/9781640532632')   来自来源“ http://192.168.1.83”的信息已被CORS政策阻止:否   请求中存在“ Access-Control-Allow-Origin”标头   资源。

为什么在COR方法上明确调用add_header'Access-Control-Allow-Origin'时仍会在Cors上出现错误?我们调用了POST,它与此调用没有相同的错误。

local.conf文件中的代码为:

upstream onix-api-server {
    # docker will automatically resolve this to the correct address
    # because we use the same name as the service: "onix-api"
    server onix-api:8000;
}
server {

    listen 80;

    location / {
        # everything is passed to Gunicorn
        proxy_pass http://onix-api-server;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            #
            # Custom headers and headers various browsers *should* be OK with but aren't
            #
            add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            #
            # Tell client that this pre-flight info is valid for 20 days
            #
            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-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        }
        if ($request_method = 'GET') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        }
    }

    location /static/ {
        alias /static/;
    }
}

0 个答案:

没有答案