I keep getting error code 403 (Forbidden (CSRF cookie not set.): /api/) even after following some responses on this kind of questions.
This is my code:
JS
import axios from 'axios';
axios.defaults.xsrfHeaderName = 'X-CSRFTOKEN';
axios.defaults.xsrfCookieName = 'csrftoken';
class App extends Component {
postHandler = (event) => {
event.preventDefault();
axios.get('http://localhost:8000/api/')
.then((response) => {
console.log(response)
})
.catch(error => alert(error));
};
}
settings.py
CORS_ORIGIN_WHITELIST = 'http://localhost:3000',
views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello!")
Anything else is set as defaults from create-react-app and django-admin startproject.
This must be added in order to work:
JS
axios.defaults.withCredentials = true;
settings.py
CORS_ALLOW_CREDENTIALS = True
view.py
from django.http import HttpResponse
from django.views.decorators.csrf import ensure_csrf_cookie
# Create your views here.
@ensure_csrf_cookie
def index(request):
return HttpResponse("Hello!")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.