6

I'm trying to validate a webhook via facebook. So facebook hits my url my-url/facebook/receive within my route in nodejs i'd do res.send(req.query['hub.challenge']); to send an http response.

I'm using KoaJS. From what i understand, Koajs merges the request and response object into ctx but when reading through the docs I can't find anything along the lines of ctx.send or similar to send a http response.

Can anyone give me some direction or links.

Thanks.

pourmesomecode
  • 4,108
  • 10
  • 46
  • 87

1 Answers1

14

To send the body of a response, you can simply do ctx.response.body = 'Hello'. There are many aliases attached to ctx, so you don't necessarily have to reference the response or request yourself. Doing ctx.body = 'Hello' would be the same as the code above.

If you wanted to set headers, you would use the ctx.set() method. For example: ctx.set('Content-Type', 'text/plain').

To access the query parameters, you would use ctx.request.query['some-key'] (or simply the alias ctx.query['some-key']).

All of the different request/response methods are documented pretty well at the Koa website along with a list of aliases attached to ctx. I highly recommend you give it a read.

Saad
  • 49,729
  • 21
  • 73
  • 112
  • 2
    I spent a few hours reading after I posted my questions and figured it out :) your answer is spot on, though. Thank you very much :) Hopefully, your answer will help someone else in the future :) – pourmesomecode Feb 15 '17 at 12:27
  • Where do you get `ctx.set` in documentation? – tonywei Dec 18 '19 at 09:20
  • [Here](https://koajs.com/#response-set-field-value-) are the docs for `ctx.response.set`. You can also see in the [response aliases](https://koajs.com/#response-aliases) section that `ctx.set` is aliased to the equivalent `response.set` method. – Saad Dec 18 '19 at 19:46