2

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you @Quentin, now the server is not throwing an error, but it looks like I am not extracting the image correctly from the request. do you have any suggestion on that also. thanks in advance
@Fadi — The last paragraph of this answer.
well, thank you again, I have tried formidable but with no success. there are many examples out there about saving the file using these library, but in my case I want to send the file to another API to handle it. here is the problem, please have a look at the code maybe you can spot where I am doing thing wrongly.
0

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);

 });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.