使用来自服务器的表单数据在客户端上获取响应

Sha*_*adH 4 javascript multipartform-data xmlhttprequest form-data fetch-api

我正在 Express 服务器上使用 Node 'form-data' 模块来构建对来自客户端浏览器的 fetch 请求的 multipart/form-data 响应(这也是使用 fetch 的多部分,但在服务器上使用 multer 可以很好地接收到)服务器)。当服务器发回表单数据响应时,我在收到响应时在获取客户端收到错误 - “无法将内容解析为 FormData。”(本机 FormData)(注意:这与不解析多部分的 Express 解析器不同,这是浏览器上的本机获取客户端不解析节点表单数据)我在服务器响应或客户端响应处理中做错了什么?

在服务器上:

const formdata = require('form-data')
app.post(req,res,next) {
// ... process the request and construct form-data response...//

var form = new formdata(); 
form.append("serverResponse", "Reply from server to fetch request from client")
res.end(form.getBuffer())
}
Run Code Online (Sandbox Code Playgroud)

在客户处

//... send request to server which has no problem, but returncannot decode the response as FormData

 return fetch(  pRequest   )
    .then(response => { 
      return response.formData()   //***this throws 'Could not parse content as FormData***
    }
    .then(result => console.log(JSON.stringify(result))
Run Code Online (Sandbox Code Playgroud)

小智 5

将响应的标题“Content-Type”设置为“multipart/form-data”。