我正在将 pdf 和标题表单数据从 React 前端发送到 Django REST 后端。我使用 [电子邮件受保护] 来执行此操作。
SendForm.js(发送前表单数据打印正常)
const formDataToSend = new FormData();
formDataToSend.append('title', formData.title);
formDataToSend.append('pdf_file', formData.pdf_file);
console.log(formDataToSend.get('title'), formDataToSend.get('pdf_file'))
const config = {
headers: {
'Content-Type': 'multipart/form-data',
'X-CSRFToken': Cookies.get('csrftoken')
},
}
const response = await axios.post(`${process.env.REACT_APP_API_URL}/api/posts/create-post/`,
formDataToSend,
config
);
这会从后端返回此错误
Bad Request: /api/posts/create-post/
[02/Mar/2024 19:15:46] "POST /api/posts/create-post/ HTTP/1.1" 400 28
我不明白的部分是,当从邮递员发送时它工作正常。下面是请求,对我来说主要区别是请求内容长度。我尝试过使用 axios 发送它的各种其他方式,但无法弄清楚。
Axios 请求损坏
POST /api/posts/create-post/ HTTP/1.1
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br, zstd
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 280
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryZWvOJOP8DWxLqAIC
Cookie: csrftoken=KpiB3K4gLN4gT3GsnPLfP9eBpOcwJ1Sb; sessionid=hgq77mclr8rynznly95gx40vjaj07cor
Host: localhost:8000
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36
X-CSRFTOKEN: KpiB3K4gLN4gT3GsnPLfP9eBpOcwJ1Sb
sec-ch-ua: "Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
工作邮递员请求
Content-Type: multipart/form-data; boundary=--------------------------998229612431930001760561
X-CSRFToken: E5khHlkBQgTXXhWhosEKtX2LOx1o8z2s
User-Agent: PostmanRuntime/7.36.3
Accept: */*
Postman-Token: c5e3e2f7-aaeb-4a16-a4da-d6f0e99e691b
Host: 127.0.0.1:8000
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Cookie: csrftoken=E5khHlkBQgTXXhWhosEKtX2LOx1o8z2s; sessionid=yvwjf72zx1ymw78uxb4p10dli5pu1wxo
Content-Length: 560891
Axios 配置
import axios from 'axios';
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.withCredentials = true;
axios.defaults.credentials = 'same-origin';
axios.defaults.withXSRFToken = true
export default axios;
我的项目中的所有其他 axios 请求都工作正常,尽管没有一个使用 FormData()。我浏览过各种论坛,它们都将其包含在帖子请求中,就像我在这里所做的那样,它对他们有用。
我想通了。我正在使用 useState 监听 formData,并通过解耦状态并添加 name: value 来刷新,但对于文件,您必须使用语法 name_of_form_input.files[0] 访问文件。