How to send a http response using koajs
Asked Answered
A

1

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.

Adrial answered 13/2, 2017 at 19:55 Comment(0)
D
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.

Decade answered 14/2, 2017 at 16:14 Comment(3)
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 :)Adrial
Where do you get ctx.set in documentation?Roop
Here are the docs for ctx.response.set. You can also see in the response aliases section that ctx.set is aliased to the equivalent response.set method.Decade

© 2022 - 2024 — McMap. All rights reserved.