Reputation: 147
When I send some data from my front-end via axios, my API give error Forbidden (CSRF cookie not set.)
I use csrf_exempt to avoid this error, however it doesn't help me
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:
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:
Forbidden (CSRF cookie not set.): /api/v1/user/restration/
"POST /api/v1/user/restration/ HTTP/1.1" 403 2868
However, when I send data via Postman everything is okay.
Upvotes: 1
Views: 4566
Reputation: 408
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.
Which is why you receive that error.
https://docs.djangoproject.com/en/1.9/ref/settings/#csrf-cookie-secure
Upvotes: 1