Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a http response using koajs

Tags:

node.js

koa

koa2

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.

like image 557
pourmesomecode Avatar asked Feb 13 '17 19:02

pourmesomecode


1 Answers

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.

like image 129
Saad Avatar answered Sep 21 '22 10:09

Saad