首页 > 解决方案 > Django - 进行 POST 时请求的资源上不存在“Access-Control-Allow-Origin”标头

问题描述

每当我在我的自定义身份验证类中发出 request.post 时,响应需要一段时间然后抛出这个错误 (502)

从源http://ec2-54-185-235-97.us-west-2.compute.amazonaws.com在“ http://54.185.235.97:8000/rest-auth/login/ ”访问 XMLHttpRequest ' 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

这是代码(如果他/她超过登录尝试次数,此代码会向用户发送电子邮件以重置密码)

headers = {'Access-Control-Allow-Origin': '*'}
requests.post(                                   
    "http://ec2-54-185-235-97.us-west-2.compute.amazonaws.com:8000/rest-auth/password/reset/",
                                            data={'email': user.email},
                                            headers=headers
                                        )

                                        user.is_blocked = True
                                        user.save()
                                        attemptsObject.delete()
                                        raise exceptions.AuthenticationFailed(('User Blocked'))

此代码在我的开发工作区中运行良好,但在我的 AWS 实例中出现了问题,这与我的 Nginx 配置有关吗?还是我需要创建自定义 CORS 中间件类?

Nginx:

upstream django_app {
  server unix:/var/www/backend/run/gunicorn.sock fail_timeout=10s;
}

server {
    listen 8000;
    server_name localhost;
    access_log /var/www/backend/logs/nginx-access.log;
    error_log /var/www/backend/logs/nginx-error.log warn;

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;


        proxy_pass http://django_app;

         }
        location ~* \.(eot|ttf|woff|woff2)$ {
            add_header Access-Control-Allow-Origin *;
        }
}

标签: djangopython-3.xamazon-web-servicesnginxpython-requests

解决方案


推荐阅读