Search code examples
node.jsrestrestify

POST request don't work in restify, getting a 500 internal server error


I'm having a little issue with an POST request in a example REST API.

I just have four callback methods for four routes:

app.get '/tasks', task.getAll
app.get '/tasks/done', task.getDone
app.get '/tasks/notdone', task.withoutDone
app.post '/tasks', task.newTask

and:

models = require '../models/models.js'

exports.getAll = (req, res, next) ->
  models.Task.find {}, 'title description, done', (err, tasks) ->
    if err then err
    res.send tasks
    do next

exports.getDone = (req, res, next) ->
  models.Task.find {done: true}, (err, tasks) ->
    if err then err
    res.send tasks
    do next

exports.withoutDone = (req, res, next) ->
  models.Task.find {done: false}, (err, tasks) ->
    if err then err
    res.send tasks
    do next

exports.newTask = (req, res, next) ->
  if req.params.title is undefined
    return next new restify.InvalidArgumentError 'Title is needed'

  taskData = 
    title: req.params.title
    description: req.params.description
    done: req.params.done

  task = new Task(taskData)
  task.save (err, data) ->
    if err
      return next new restify.InvalidArgumentError(JSON.stringify(error.errors))
    else
      res.json(data)

    res.send 201, task

So, you can find the code here in a unique gist.

The trace when i run

curl -i -X POST -d '{"title": "hello world", description: "lorem ipsum dolor amet", "done": true}' http://localhost:8080/tasks

return's me a 500 internal head in the response:

HTTP/1.1 500 Internal Server Error
Content-Type: application/json
Content-Length: 59
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, Api-Version, Response-Time
Access-Control-Allow-Methods: GET, POST
Access-Control-Expose-Headers: Api-Version, Request-Id, Response-Time
Connection: Keep-Alive
Content-MD5: QFnWTtR6KfhLtGqWpGWZog==
Date: Mon, 17 Mar 2014 15:12:00 GMT
Server: task-API
Request-Id: 7d71a510-ade6-11e3-bd80-292785b198e2
Response-Time: 1

{"code":"InternalError","message":"restify is not defined"}

Solution

  • Restify has a similar design as expressjs in terms of error handling. It swallows uncaught exceptions and send them back to the browser, in JSON format accompanied with HTTP 500 error, instead of printing them at the console.

    The message "restify is not defined" typically means you forgot to call var restify = require('restify'); somewhere in your script.

    You can also use the following snippet to pinpoint the location of the error at console:

    server.on('uncaughtException', function (req, res, route, err) {
        console.log('uncaughtException', err.stack);
    });