[英]How to fix “Forbidden (CSRF cookie not set.)”
When I send some data from my front-end via axios, my API give error Forbidden (CSRF cookie not set.) 当我通过axios从前端发送一些数据时,我的API发出错误“禁止”(未设置CSRF cookie)。
I use csrf_exempt to avoid this error, however it doesn't help me 我使用csrf_exempt来避免此错误,但是它对我没有帮助
views.py: 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()
This is my code on React: 这是我在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>
When I send data from UI I have the error: 当我从UI发送数据时,出现错误:
Forbidden (CSRF cookie not set.): /api/v1/user/restration/
禁止(未设置CSRF cookie):/ api / v1 / user / restration /
"POST /api/v1/user/restration/ HTTP/1.1" 403 2868
“ POST / api / v1 /用户/ restration / HTTP / 1.1” 403 2868
However, when I send data via Postman everything is okay. 但是,当我通过邮递员发送数据时,一切正常。
If you have CSRF_COOKIE_SECURE to be True in your settings file, then the cookie will be marked as "secure" and will need an HTTPS connection. 如果您在设置文件中将CSRF_COOKIE_SECURE设置为True,则cookie将被标记为“安全”,并且需要HTTPS连接。
Which is why you receive that error. 这就是为什么您收到该错误的原因。
https://docs.djangoproject.com/en/1.9/ref/settings/#csrf-cookie-secure https://docs.djangoproject.com/zh-CN/1.9/ref/settings/#csrf-cookie-secure
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.