【问题标题】:How to fix "Forbidden (CSRF cookie not set.)"如何修复“禁止(未设置 CSRF cookie。)”
【发布时间】:2019-12-29 11:32:52
【问题描述】:

当我通过 axios 从前端发送一些数据时,我的 API 给出错误 Forbidden (CSRF cookie not set.)

我使用 csrf_exempt 来避免这个错误,但这对我没有帮助

views.py:

@csrf_exempt
def registration(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        if not is_user_data_valid_for_create(data):
            return HttpResponseBadRequest()
        user_role = Role.objects.get(pk=1)
        user = User.create(
            first_name=data['first_name'],
            last_name=data['last_name'],
            email=data['email'],
            password=data['password'],
            role=user_role
        )
        return HttpResponse("Success,{} your account created!".format(user.first_name), status=201)
    return HttpResponseBadRequest()

这是我在 React 上的代码:

constructor(props) {
        super(props);

        this.state = {
            first_name: '',
            last_name: '',
            email: '',
            password: ''
        }
    }

    changeHandler = event => {
        this.setState({[event.target.name]: event.target.value})
    };

    submitHandler = event => {
        event.preventDefault()
        console.log(this.state);
        axios
            .post('http://127.0.0.1:8000/api/v1/user/restration/', this.state)
            .then(response => {
                console.log(response)
                console.log(response.data)
            })
            .catch(error => {
                console.log(error)
            })
    };

<form onSubmit={this.submitHandler}>
                <div className="user-data">
                    <div className="form-group">
                        <label>First Name</label>
                        <input type="text" placeholder="John" name="first_name" value={first_name}
                               onChange={this.changeHandler} className="form-control"/>
                            </div>
...
                  <div className="sign-up-w">
                      <button type="submit" className="btn-primary sing-up">SIGN UP</button>
                  </div>
</form>

当我从 UI 发送数据时出现错误:

禁止(未设置 CSRF cookie。):/api/v1/user/restration/

“POST /api/v1/user/restration/HTTP/1.1”403 2868

但是,当我通过 Postman 发送数据时,一切正常。

【问题讨论】:

    标签: python django api csrf


    【解决方案1】:

    如果您的设置文件中的 CSRF_COOKIE_SECURE 为 True,则 cookie 将被标记为“安全”并且需要 HTTPS 连接。

    这就是您收到该错误的原因。

    https://docs.djangoproject.com/en/1.9/ref/settings/#csrf-cookie-secure

    【讨论】:

    • 不,我没有在设置中设置 CSRF_COOKIE_SECURE
    • 尝试,将 CSRF_COOKIE_SECURE 设置为 false,在您的 settings.py 中明确设置
    • 它没有帮助,因为我知道 django 默认为 CSRF_COOKIE_SECURE 设置 False
    • 您使用的是 django rest 框架还是只使用 django?
    • 只是 django,重要吗?
    猜你喜欢
    • 2012-05-03
    • 2016-11-26
    • 2022-09-27
    • 2020-01-16
    • 2021-10-08
    • 1970-01-01
    • 2018-04-10
    • 2019-12-18
    • 1970-01-01
    相关资源
    最近更新 更多