Recently I have to implement REST API for my project. I’ve decided to use all goodies, what modern Web-Dev has. I found this example on Node.JS and Express.JS using MongoDB and to be able implement my requirements I forked it here. I started work on it, and it looks simple task, but it turned out kinda buggy 🙂
I executed “node server.js” and it works fine with mocha test. But when I call my REST url via third party software, I have an error like this:
After 2 days of troubleshooting I found solution. Funny, that it’s pretty simple 🙂
First of all I found that when request is sent to my REST server by my 3rd party tool has wrong response Content-type (text/plain instead of application/json). So I played with Express.JS API:
- res.set(“Accept”, “application/json”)
- even res.json() instead of res.send()
Then I typed error mentioned above into Google. Not from the first time I found solution, because this error is not so popular in web.
First, I found info that “bodyParser()” ignore Content-type. It gave me an idea that can be some issue with parsing body-less request. I was disappointed with no solution, but nevertheless I tried to re-write search query in Google 🙂 And fortunately I found Second hint for me. And It’s super awesome:
if I comment out: app.use(express.bodyParser());, the error disappears.
And big bang, it works 🙂 In my server.js I just did the same. And now my 3rd party tool call JSON service and response is received with application/json Content-type.
But as always I do – It’s very easy way for me to resolve issues 🙂 (so this is not the end of story though). I ran my Mocha tests and they were failed. 🙂
And I start research again. Found this post about the same (not using bodyParser()) which gave me an idea, that in fact express.json() cause the issue. Something similar here as well. But then I realized that my
npm install express
has installed 3.0.0.apha4 version and I decided to upgrade:
npm install firstname.lastname@example.org
with no exact version pointed npm for some reason install not the latest version.
And u know – issue totally resolved. After server re-run all works fine: express.bodyParser(), express.json(), mocha test are passed and even 3rd party call to REST API works fine 🙂
There is good info now: I realized now, that I may use express.json() only. Because really – I don’t need multipart() at all.
The good point of this story – that Google Search query may solve all your troubles, than be eager and try to dig as deep as it possible and then so deep as impossible 🙂 And result of troubleshooting may be very simple so you even can’t imagine it when start work on some project.
The bad point of this story – bodyParser() was buggy in old version, but in the latest version issues are fixed. Need always be sure u are using stable version of code.