【发布时间】:2020-12-18 09:24:17
【问题描述】:
我正在使用 Django 和 React 创建一个全栈应用程序。
我创建了一个使用 cookie 的组件查找。这是我的代码:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function lookup(method, endpoint, callback, data) {
let jsonData;
if (data){
jsonData = JSON.stringify(data)
}
const xhr = new XMLHttpRequest()
const url = `http://localhost:8000/api${endpoint}`
xhr.responseType = "json"
const csrftoken = getCookie('csrftoken');
xhr.open(method, url)
xhr.setRequestHeader("Content-Type", "application/json")
if (csrftoken){
xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest")
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")
xhr.setRequestHeader("X-CSRFToken", csrftoken)
}
xhr.onload = function() {
callback(xhr.response, xhr.status)
}
xhr.onerror = function (e) {
console.log(e)
callback({"message": "The request was an error"}, 400)
}
xhr.send(jsonData)
}
export function createPost(newPost, callback){
lookup("POST", "/posts/create/", callback, {content: newPost})
}
export function loadPosts(callback) {
lookup("GET", "/posts/", callback)
}
此代码导致我的前端出现此错误:(后端工作正常) 从源“http://localhost:3000”访问“http://localhost:8000/api/posts/”处的 XMLHttpRequest 已被 CORS 策略阻止:Access-Control-Allow- 不允许请求标头字段 http_x_requested_with预检响应中的标头。
现在,我意识到如果我删除这个:
if (csrftoken){
xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest")
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")
xhr.setRequestHeader("X-CSRFToken", csrftoken)
}
我的代码运行良好。
- 为什么会这样?如果还有什么需要上传的,请告诉我
- 如果只是我的个人项目,您认为跳过 csrftoken 是否合理?
【问题讨论】:
标签: django reactjs csrf csrf-token