Fadi
Fadi

Reputation: 203

forward upload image request using multer (javascript, express)

I am using the express server as an API gateway to my microservices, in which I am processing images and store them in a database. the problem summarizes as follows: in the express server, I need to forward the image received in a post request from the client and forward it to the web service that can handle image processing. It turns out that I need to parse the image before I can forward it to the next API, the error I am getting is Unexpected token - in JSON at position 0

Her is my client that sends the image to the express server(my gateway)

  function uploadWithFormData() {
    const formData = new FormData();
    formData.append("file", file);
 
fetch('/upload', {
        method: "POST",
        headers: {
            "content-type": "application/json",
                   },
        body: data
    }).then(handleResponse)
        .catch(handleError);
    uploadImage(formData);

  }

and this is my express serve that should handle the request and forward it to another web service



app.post("/upload", function (req, res) {
 const form = formidable({ multiples: true });
 form.parse(req, (err, fields, files) => {
 const response = res.json({ fields, files });

 let formData = new FormData();
 formData.append('file', fs.createReadStream(req.files.file.path), req.files.file.name);

 uploadImageAPI(response).then(
   res.status(201).send()
 ).cache(res.status(412).send())
});


I have tried to make some consol.log inside the function to see the req but the request fails before it enters the function, because express could not pars the image. I saw some people doing this using the multer library but I could not mange that in my case any suggestions?

Upvotes: 2

Views: 1387

Answers (2)

Fadi
Fadi

Reputation: 203

Part of the solution is to remove the JSON header as @Quentin said in his answer. However, the code that solved the problem is as following :

const multer = require('multer');
const upload = multer();

app.post("/upload", upload.any(), (req, res) => {
const { headers, files } = req;
const { buffer, originalname: filename } = files[0];
headers['Content-Type'] = 'multipart/form-data';

const formFile = new FormData();
formFile.append('file', buffer, { filename });
fetch(URL, {
method: "POST",
body: data
 }).then(handleResponse)
.catch(handleError);

 });

Upvotes: 0

Quentin
Quentin

Reputation: 943214

You're posting a FormData object, which will be converted to multipart/form-data.

You aren't posting JSON.

You have set "content-type": "application/json" so you claim you are posting JSON.

The server tries to decode the "JSON", fails, and throws the error.


Don't override the Content-Type header. fetch will generate a suitable one automatically when you pass it a FormData object.

Do use a body parsing module which supports multipart requests. body-parser does not, but its documentation links to several that do.

Upvotes: 2

Related Questions