Javascript 将HTML表单操作替换为Web服务器的获取api

Javascript 将HTML表单操作替换为Web服务器的获取api,javascript,express,xmlhttprequest,fetch,Javascript,Express,Xmlhttprequest,Fetch,我使用HTML表单操作属性将文件存储在我的电脑上,然后在我的Express Web服务器上处理该请求。 当我现在尝试在表单的submit按钮上用eventlistener代替action属性来发送post请求时,我无法让它工作 我收到一条错误消息400错误请求 取来 HTML 根据您的html和获取代码,您的express代码应如下所示: const express = require('express') const app = express(); const path = require(

我使用HTML表单操作属性将文件存储在我的电脑上,然后在我的Express Web服务器上处理该请求。
当我现在尝试在表单的submit按钮上用eventlistener代替action属性来发送post请求时,我无法让它工作

我收到一条错误消息400错误请求

取来 HTML
根据您的html和获取代码,您的express代码应如下所示:

const express = require('express')
const app = express();
const path = require('path')
const things = require('./routes/things')
const fileUpload = require('express-fileupload')

app.use('/upload', fileUpload({
  createParentPath: true
}));

app.post('/upload', (req, res) => {
    const { inpFile } = req.files;

    inpFile.mv(path.join(__dirname, 'files', inpFile.name))
      .then(() => res.send('File uploaded!'))
      .catch(err => res.status(500).send(err));
})
您需要将中间件绑定到应用程序:

app.use('/upload', fileUpload({
  createParentPath: true
}));
您的文件对象应该位于req.files.inpFile中


您还需要从提取请求中删除标题。

根据您的html和提取代码,您的express代码应该如下所示:

const express = require('express')
const app = express();
const path = require('path')
const things = require('./routes/things')
const fileUpload = require('express-fileupload')

app.use('/upload', fileUpload({
  createParentPath: true
}));

app.post('/upload', (req, res) => {
    const { inpFile } = req.files;

    inpFile.mv(path.join(__dirname, 'files', inpFile.name))
      .then(() => res.send('File uploaded!'))
      .catch(err => res.status(500).send(err));
})
您需要将中间件绑定到应用程序:

app.use('/upload', fileUpload({
  createParentPath: true
}));
您的文件对象应该位于req.files.inpFile中


您还需要从提取请求中删除标题。

'Content-Type':'multipart/form data'您不必将其设置为
fetch()
出于好奇,当将
FormData
对象作为
主体
值传递时,将在内部执行此操作,为什么要这样做?您还将post名称设置为
inpFile
append('inpFile'
),但使用了
sampleFile
req.files.sampleFile
)在服务器代码中,
上的
change
事件在哪里?只有通过
change
事件才能获取文件。直到您现在提到更改事件,我才知道它。
'Content-Type':'multipart/form data'
您不必将其设置为
fetch()
在将
FormData
对象作为
主体
值传递时会在内部执行此操作出于好奇,您为什么要这样做?您还将post name设置为
inpFile
append(
inpFile'
),但使用了
sampleFile
req.files.sampleFile
)在服务器代码中,
上的
change
事件在哪里?只有通过
change
事件才能获取文件。直到您现在提到更改事件,我才知道它。
app.use('/upload', fileUpload({
  createParentPath: true
}));