我正在尝试将表单数据上传到Express服务器。在我的express js服务器上,我有以下内容:
router.post('/uploads/:id', function(req, res) {
res.send(req.body);
const title = req.body.title;
const file = req.file;
});
我发送回req.body以查看它是否命中了相应的url。当我使用以下命令时:
const response = await fetch('https://example.com/uploads/1234', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(form) });
const responseData = await response.json();
console.log(responseData);
我得到了转换为json的FormData的响应。当我这样运行它时:
const file = fs.createReadStream(`${desktopDir}/ai2html-output/home-pro-Artboard_1.jpg`);
const title = 'My file fsf';
const form = new FormData();
form.append('title', title);
form.append('file', file);
const response = await fetch('https://example.com/uploads/1234', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body: form });
const responseData = await response.json();
然后返回一个空对象:{}
我必须在express服务器上设置一些东西才能接收表单数据吗?我需要某种类型的中间件吗?
这里也是我的请求头从服务器响应:
:method: POST
:path: /uploads/1234
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
content-length: 17
content-type: multipart/form-data
origin: file://
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
1条答案
按热度按时间mwkjh3gx1#
我必须在express服务器上设置一些东西才能接收表单数据吗?
是的,要在 Express 服务器上处理
multipart/form-data
,您必须配置中间件。例如
multer
库。Demo:
服务器.js
上传.js
"Content-Type": "multipart/form-data"
即可。如果你想将上传的文件保存到一个特定的文件夹“uploads/”中,并且文件的标题带有req.body.title,请将此配置添加到multer中: