sholladay / pogo

Server framework for Deno

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Setting status code isn't working

chris-carrington opened this issue · comments

Thank you so much for creating pogo! The implementation + documentation is inspiring, I'm happy here!

I'm trying to send a 401 status code and it's not working. I'm getting a 200 if I only try .status or .code or both. May I have some guidance on what I'm doing wrong please?

Thank you!

import pogo from 'https://deno.land/x/pogo/main.js'
import { Status as status } from 'https://deno.land/std/http/http_status.ts';

let app = pogo.server({ port : 3000 })

app.router.get('/', (req) => {
  req.response.status = 401
  req.response.code(status[401])
  console.log(req.response.status) // logs Unauthorized but Insomnia + browser say 200

  return 'Hello world!'
})

app.start()

I figured it out, this or the comment works, thank you!

app.route({
  path: '/',
  method: 'GET',
  handler (req, h) {
    req.response.status = 401
    return req.response
    // return h.response().code(403)
  }
})

Thank you for the kind words. I am glad you figured it out and are enjoying Pogo! 🙌

As you noticed, you can modify the status code of the default response instance that already exists at request.response when your route handler is called. That is officially supported, however I find that approach less than ideal because it mutates objects that are external to the handler function.

I like pure functional programming, so I recommend this pattern (as done in your code comment):

server.route({
    method : 'GET',
    path   : '/',
    handler(request, h) {
        return h.response('Hello, World!').code(403);
    }
});

Regardless of whether you use request.response or h.response(), you should use response.code() instead of assigning a value to response.status directly, as that will make it easier for you to change other details about the response by chaining additional response methods.

See the response.code() documentation for some other tips related to setting the status code.

It's also worth noting that I recently added a bang module that will be useful for responding with error codes like 403 Forbidden by throw-ing error objects. That feature is not yet documented or officially released, because there are a few things that bother me about the current implementation, but it's coming soon. (It is the equivalent of hapi's boom module, in case you are familiar with that.)

If you have any more questions or feedback, feel free to post them here or find me in the Deno gitter chat or the hapi Slack chat.