当我通过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 /用户/ RESTRATION / HTTP / 1.1” 403 2868
但是,当我通过Postman发送数据时,一切正常。
答案 0 :(得分:0)
如果您在设置文件中将CSRF_COOKIE_SECURE设置为True,则cookie将被标记为“安全”,并且需要HTTPS连接。
这就是为什么您收到该错误的原因。
https://docs.djangoproject.com/en/1.9/ref/settings/#csrf-cookie-secure