Bad Request uploading file to hapi

1.2k views Asked by At

I have followed many tutorials and done many combination but I still cannot get hapi to get the payload properly and I always get a 400 bad request reply.

This is the code in the frontend:

    public uploadFile = (file: File) => {
        console.log(file.name); /// <--- Correctly displays the name, so the files seems to be loaded correctly

        const url = "/api/upload_resource";
        const formData = new FormData();

        formData.append('file', file);
        formData.append('something', "else");

        fetch(url, {
          method: 'POST',
          headers:{"Content-Type": "multipart/form-data"},
          body: formData
        })
        .then((response: any) => { console.log(response);/* Done. Inform the user */ })
        .catch((e) => { /* Error. Inform the user */ })
      }

And this is the entry in server.route

            { path: "/api/upload_resource", method: "POST",
                        options:{handler: (e,h)=>{return h.response({}).code(200);},
                                 payload:{ maxBytes: 30485760, parse: true, output:'file',
                                           allow: ['multipart/form-data', "application/JSON"]
                                         }
                                 }
            },

I'm using hapi 19.x

1

There are 1 answers

0
javanoob On

Solved,

TLDR: remove the header in the fetch call and add another key multipart: {output: "file"} in options.payload in the server route item

Now this is how I figured out:

  1. I managed to add a failAction method to the payload to be able to get a more verbose error

payload:{failAction: async (r:any, h:any, e:any) => {console.log(e.message);}, maxByt...

  1. the failAction reported the following error

Invalid content-type header: multipart missing boundary

  1. Ok, back to google to check what the heck a boundary is. After somehow managing to add a boundary, I got a new error message, clearly indicating progress

Unsupported Media Type

I was already familiar with that error message. And, according to many answers in other post, the solution seemed to be adding "Content-Type": "multipart/form-data" to the header. But that led to the "Bad Request Message" issue, and the posts referencing this error suggested to remove it.

So I knew the problem was the "Unsupported Media Type" error message and that the solution should be in the backend not the frontend. So I just searched "Unsupported Media Type hapi" and discovered the missing one payload option in the route.