【问题标题】:DRF+Axios: some requests fail with `ERR_NETWORK` or `ERR_BLOCKED_BY_CLIENT`DRF+Axios:一些请求因“ERR_NETWORK”或“ERR_BLOCKED_BY_CLIENT”而失败
【发布时间】:2022-10-20 16:44:09
【问题描述】:

这不是一个问题,更像是对这个常见问题的答案。

我有一个用NextJsDjango+DRF 构建的Dashboard,我使用axios 作为HTTP 客户端。

我注意到我的一些requests 通过了,而另一些则没有(主要是获取例如公司每月/每年付款/费用的请求)。

在下面,您将找到解决此问题的方法。

【问题讨论】:

    标签: django browser axios cors


    【解决方案1】:

    可能解决此问题的解决方案:

    • 在您的 django 服务器 settings.py 上正确设置 CORS
        # CSRF
        # Either Update Axios settings or Django Settings
        CSRF_COOKIE_NAME = 'XSRF-TOKEN'
        CSRF_HEADER_NAME = 'HTTP_X_XSRF_TOKEN'
    
        # CORS
        CORS_ALLOW_ALL_ORIGINS = True # Do not run your production server with this setting
        CORS_ALLOW_CREDENTIALS = True
    
        from corsheaders.defaults import default_headers
        CORS_ALLOW_HEADERS = list(default_headers) + [
            'x-xsrf-token',
            'access-control-allow-headers', # this one is important
        ]
    
        CSRF_TRUSTED_ORIGINS = [
            'http://localhost:8000',
            'http://localhost:3000'
        ]
    
        CORS_ORIGIN_WHITELIST = [
            'http://localhost:8000',
            'http://localhost:3000',
        ]
    
    • 如果您正在运行 Ublock Origin 或任何此类浏览器扩展,请将其关闭 127.0.0.1localhost
    • 对于Brave browser,关闭127.0.0.1localhost 的屏蔽
    • 就是这样,希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      我在 Django(不是 DRF)中解决了类似的问题,它在尝试在 compose 中部署 django+gunicorn+nginx 时重现。

      但我使用https://pypi.org/project/django-cors-headers/

      #settings.py 只需添加:

      INSTALLED_APPS = [
          'corsheaders',
      
      ]
      
      MIDDLEWARE = [
          'corsheaders.middleware.CorsMiddleware',
      ]
      
      CORS_ALLOWED_ORIGINS = [
      #and add your site address with ports
          "http://127.0.0.1:8001",
          "http://localhost:8001",
      ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-08
        • 1970-01-01
        相关资源
        最近更新 更多