如何修复"Forbidden (CSRF cookie not set.)"



当我通过 axios 从前端发送一些数据时,我的 API 给出错误 禁止(CSRF cookie 未设置。

我使用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

但是,当我通过邮递员发送数据时,一切都很好。

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

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

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

最新更新