Using Restify & Mongoose, I built a basic REST API. Everything is working fine as long as I send JSON content with application/json
as a content.
But now I need to send an image along with content, so I switched to multipart/form-data
for a specific route. And it don't seem to get the content at all.
Here’s the basic setup sent to my API with Insomnia:
Pretty simple. The Mongodb Model only require filename
and url
at the moment (I’ll deal with the file itself once this will work).
And this is what I get as a response from the server:
{
"code": "Internal",
"message": "Media validation failed: url: Path `url` is required., filename: Path `filename` is required."
}
So it’s saying it didn't got any of the fields content.
The Timeline shows that the fields have been sent:
> POST /medias HTTP/1.1
> Host: localhost:3030
> User-Agent: insomnia/6.0.2
> Content-Type: multipart/form-data; boundary=X-INSOMNIA-BOUNDARY
> Accept: */*
> Content-Length: 221
| --X-INSOMNIA-BOUNDARY
| Content-Disposition: form-data; name="filename"
| test.jpg
| --X-INSOMNIA-BOUNDARY
| Content-Disposition: form-data; name="url"
| https://images.test.com/test.jpg
| --X-INSOMNIA-BOUNDARY--
* We are completely uploaded and fine
< HTTP/1.1 500 Internal Server Error
< Server: TestServer
< Content-Type: application/json
< Content-Length: 125
< Connection: Keep-Alive
< Content-MD5: KI89enLnYv9oMJxg5k4MXA==
< Date: Sun, 12 Aug 2018 22:50:31 GMT
< Request-Id: b20babc1-9f1b-466b-af7c-13d385cd8023
< Response-Time: 6
* Received 125 B chunk
* Connection #65 to host localhost left intact
Here’s my function:
server.post('/medias', (req, res, next) => {
if (!req.is('multipart/form-data')) {
return next(
new errors.InvalidContentError(`Expects 'multipart/form-data'`)
)
}
let data = req.body || {}
let media = new Media(data)
media.save((err) => {
if (err) {
return next(new errors.InternalError(err.message))
next()
}
res.send(201)
next()
})
})
A console.log
on the req.body
reveal that it’s empty. I’ve consoled the req
itself to see if the datas could be stored anywhere else, but I couldn’t find anything.
What did I missed here? Thank you in advance.