【发布时间】:2023-03-25 18:05:01
【问题描述】:
如果问题更多是初学者,但我已经使用 django 后端和反应前端构建了一个应用程序,我很抱歉,现在我正在尝试使用以下代码在创建端点上为 post 请求实现 csrf 令牌.
getCookie.js
import React from 'react';
const getCookie = (name) => {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const 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;
}
export default getCookie;
CsrfToken.js
import React from 'react';
import getCookie from './getCookie';
var csrftoken = getCookie('csrftoken');
const CSRFToken = () => {
return (
<input type="hidden" name="csrfmiddlewaretoken" value={csrftoken} />
);
};
export default CSRFToken;
创建.js
import React from 'react';
import axios from "axios";
import CsrfToken from './CsrfToken';
const Create = () => {
...
const options = {
headers: {
'Content-Type': 'application/json',
}
};
const handleSubmit = (e) => {
e.preventDefault();
axios.post("http://xyz/create/", fields, options)
.then(response => {
...
};
return (
<>
<div className="somecontainer">
<div className="row">
<div className="col-md">
<Form onSubmit={handleSubmit}>
<CsrfToken /> < ==== CSRF TOKEN COMPONENT
<Form.Group className="sm-3" controlId="username">
<Form.Control
size="lg"
className="submit-button-text"
type="name"
placeholder="Enter username"
value={fields.name}
onChange={handleFieldChange}
/>
</Form.Group>
...
假设上面的脚本是正确的(如果不是,请告诉我),在浏览器中使用网络选项卡内的 chrome 时,我是否检查 csrf 功能是否实际启用生成一个发布请求?
我在这里看不到:
【问题讨论】:
标签: javascript python reactjs python-3.x django