Search code examples
javascriptxmlhttprequestmultipartform-datafetch-apiform-data

fetch response on client with form-data from server


I am using the Node 'form-data' module on an Express server to construct a multipart/form-data response to a fetch request from the client browser (which also a multipart using fetch, but is received fine at the server using multer on the server). When server sends back a form-data response I get error at the fetch client on receipt of response - "Could not parse content as FormData."(the native FormData) (Note: This is different from Express parsers not parsing multipart, this is the native fetch client on browser not parsing a node form-data) What am I doing wrong in the server response or client repsonse processing?

At the server:

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())
}

At the Client

//... 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))

Solution

  • Set the header "Content-Type" of your response to "multipart/form-data".