浏览器抱怨访问控制标头丢失,甚至认为它在那里

时间:2019-10-24 10:46:12

标签: django cors

我正在使用一个简单的Django中间件来设置访问控制标头。

class CorsMoiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Credentials"] = True
        response["Access-Control-Allow-Methods"] = "GET"
        response["Access-Control-Max-Age"] = "3600"
        response["Access-Control-Allow-Headers"] = "Content-Type, Accept, X-Requested-With, remember-me"
        return response

使用curl我可以清楚地看到正确的标题。

< HTTP/1.1 200 OK
< Date: Thu, 24 Oct 2019 09:40:35 GMT
< Server: WSGIServer/0.2 CPython/3.7.4
< Content-Type: application/json
< Vary: Accept, Cookie
< Allow: GET, POST, HEAD, OPTIONS
< Access-Control-Allow-Origin: *
< X-Frame-Options: SAMEORIGIN
< Content-Length: 176
< Access-Control-Allow-Credentials: True
< Access-Control-Allow-Methods: GET
< Access-Control-Max-Age: 3600
< Access-Control-Allow-Headers: Content-Type, Accept, X-Requested-With, remember-me
...

但是,如果我尝试从JavaScript fetch进入url,则会在控制台中看到以下错误。

Access to fetch at 'http://localhost:8000/api/v1/todo' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

2 个答案:

答案 0 :(得分:0)

尝试:

response["Access-Control-Allow-Credentials"] = 'true'

答案 1 :(得分:0)

fetch ed网址中添加斜杠即可解决问题。