这是一个教育项目,不是为了生产.我不打算让用户登录.
我可以在没有用户登录的情况下使用CSRF令牌向Django进行POST通话吗?我可以不使用jQuery来完成这项工作吗?我在这里有点不知所措,肯定混淆了一些概念.
在JavaScript方面,我找到了这个redux-csrf包.我不知道如何使用Axios将其与我的POST
动作结合起来:
export const addJob = (title, hourly, tax) => {
console.log("Trying to addJob: ", title, hourly, tax)
return (dispatch) => {
dispatch(requestData("addJob"));
return axios({
method: 'post',
url: "/api/jobs",
data: {
"title": title,
"hourly_rate": hourly,
"tax_rate": tax
},
responseType: 'json'
})
.then((response) => {
dispatch(receiveData(response.data, "addJob"));
})
.catch((response) => {
dispatch(receiveError(response.data, "addJob"));
})
}
};
在Django方面,我已经阅读了this documentation篇关于CSRF的文章,以及this篇关于如何使用基于类的视图的文章.
以下是我目前的看法:
class JobsHandler(View):
def get(self, request):
with open('./data/jobs.json', 'r') as f:
jobs = json.loads(f.read())
return HttpResponse(json.dumps(jobs))
def post(self, request):
with open('./data/jobs.json', 'r') as f:
jobs = json.loads(f.read())
new_job = request.to_dict()
id = new_job['title']
jobs[id] = new_job
with open('./data/jobs.json', 'w') as f:
f.write(json.dumps(jobs, indent=4, separators=(',', ': ')))
return HttpResponse(json.dumps(jobs[id]))
我试着使用csrf_exempt
装潢师只是为了暂时不必担心这个问题,但这似乎不是它的工作原理.
我在模板中添加了{% csrf_token %}
个.
这是我的getCookie
种方法(从Django docs偷来的):
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();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
I've read我需要更改Axios CSRF信息:
var axios = require("axios");
var axiosDefaults = require("axios/lib/defaults");
axiosDefaults.xsrfCookieName = "csrftoken"
axiosDefaults.xsrfHeaderName = "X-CSRFToken"
我应该把实际的 token 放在哪里,我从拨打getCookie('csrftoken')
得到的值?