我正在try 将表单数据上传到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);
我将FormData的响应转换为json. 然而,当我这样运行它时:
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