“No 'Access-Control-Allow-Origin' header is present on the requested resource” in django

前端 未结 11 724
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 16:44

I am newbie to django and using it as back end for an application that creates users. In front end the code for posting the user name is :

var xobj = new XM         


        
11条回答
  •  被撕碎了的回忆
    2020-12-02 17:19

    Old question, but I'm not seeing this solution, which worked for me, anywhere. So hoping this can be helpful for someone.

    Cross-origin requests in this context are only possible if the partner site's server allows it through their response headers.

    I got this to work in Django without any CORS middleware by setting the following headers on the response:

    response["Access-Control-Allow-Origin"] = "requesting_site.com"
    response["Access-Control-Allow-Methods"] = "GET"
    response["Access-Control-Allow-Headers"] = "requesting_site.com"
    

    Most answers on StackOverflow seem to mention the first one, but not the second two. I've just confirmed they are all required. You'll want to modify as needed for your framework or request method (GET, POST, OPTION).

    p.s. You can try "*" instead of "requesting_site.com" for initial development just to get it working, but it would be a security hole to allow every site access. Once working, you can restrict it for your requesting site only to make sure you don't have any formatting typos.

提交回复
热议问题