Access custom request headers node express - node.js

I am building a web api with Express and have not found information on accessing incoming custom request headers.
I will be expecting, for instance, that an incoming post request have a provider_identifier header. When I receive the request, I need to access that header information to validate their subscription.
Can someone point me in the right direction/provide advice on this?
router.post('myendpoint/', function(req, res){
var providerId = req.????;
});

Answering my own question here... was kindof a DUH moment for me.
Using above example, simply reference the headers collection like so:
var providerId = req.headers.provider_identifier;
One note: Use an underscore rather than a dash. "provider-identifier" doesn't work, but "provider_identifier" does.

Related

Node.js: is request unique?

In node.js, when using https-module and createserver. When user makes request to httpsserver, is request unique or can different request has same request (id?). If it is unique, which property should be to use?
The request argument in an http request handler is a Javascript object and every one is unique. They are never reused. That object is documented here.
There is no such thing as a request ID in the node.js http library. If you want to make your own request ID, you can do that yourself by just assigning a symbol as a property of the request object. You can pick any property name to use that does not conflict with existing properties.
Since this is a bit of an unusual request, I'd ask you why you're trying to do this because there may be a better way to solve your problem than trying to make a request ID. If you show your actual code and what you're trying to do, we could probably help you more specifically.
If you were using Express, you could set your own request ID with some middleware like this:
// set request ID
let reqCntr = 0;
app.use((req, res, next) => {
req._localID = reqCntr++;
next();
});
Just place this middleware before any other request handlers that wish to use the id. You can pick any non-conflicting property name. I picked _localID.

How to send a http response using koajs

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.
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.

Fetch post data after a request in NodeJS

i' m a bit new to Node, so question may be stupid...
I am sending a POST request to a website (through http.request) and I want to be able to use the invisible POST data I get along the response.
I hope this is achievable, and I think so since I am able to preview those data in Chrome debugger.
PS : I understand that we can use BodyParser to parse and get those while listening for a POST call server side, but I have found no example of how to use it coupled with an http.request.
Thanks !
If the body of the HTTP response contains JSON, then you need to parse it first in order to turn it from a string into a JavaScript object, like this:
var obj = JSON.parse(body);
console.log(obj.response.auth_token);
More info on various ways of sending a POST request to a server can be found here: How to make an HTTP POST request in node.js?
Edit : So we figured it out in the comments. The value I needed was in the form to begin with, as a hidden field. My error was to think it was generated afterward. So I'll just grab it first then login, so I can use it again for future POST requests on the website.

Does the request object in Node.js contain any navigator.userAgent type of information?

I've setup a Node.js server that gets some contact form data and forwards it to my email. I'd like to be able to forward some information about the user's browser along with the form data.
Is any of that information contained in the request object in some form ? Kind of like the navigator.userAgent string that is available on the client ?
Or should I include that string in the data sent out, manually, myself?
I was thinking of something like :
var httpServer = http.createServer(function (request, response)
{
var browserID = request.navigator.userAgent;
});
Thanks!
I was testing this out myself in express, and you can find the user-agent string in:
request.header['user-agent']
and you can see it in the HTTP specification in 14.43 here.
In the future, you can simply examine the request object either with console.log() or with the debugger and see exactly what's in it. I find that is often ultimately more educational than trying to find things in documentation somewhere.

Express.js: Is this a RESTful interface?

I am pretty new to node and express.js and I'm new to the concept of REST applications as well. I want to code a typical CRUD app, some sort of diary. Hence, I have a collection of entries, can view a single entry and can add, edit and delete an entry.
I'm not quite getting yet, how URi's have to be set up to represent a REST conform API. I would create something like this in my app.js:
// GET REQUEST ROUTING
app.get('/', diary_router.home);
app.get('/entries/', diary_router.listEntries);
app.get('/entries/:id', diary_router.getSingleEntry);
// POST REQUEST ROUTING
app.post('/entries/', diary_router.addEntry);
// PUT REQUEST ROUTING
app.put('/entries/', diary_router.updateEntry);
// DELETE REQUEST ROUTING
app.delete('/entries/', diary_router.deleteEntry);
Could that be called a REST conform interface? Should I rather add the respective action in the routes, such as this and does the item-ID need to be shown in the URL for PUT and DELETE actions, too?:
// GET REQUEST ROUTING
app.get('/', diary_router.home);
app.get('/entries/', diary_router.listEntries);
app.get('/entries/show/:id', diary_router.getSingleEntry);
// POST REQUEST ROUTING
app.post('/entries/add/', diary_router.addEntry);
// PUT REQUEST ROUTING
app.put('/entries/update/:id', diary_router.updateEntry);
// DELETE REQUEST ROUTING
app.delete('/entries/delete/:id', diary_router.deleteEntry);
What would be best practice here? Any help is much appreciated.
B.
In the loose definition of REST that we seem to have converged on in web-land, the first option seems to fit best.
Edit: and yes, you should specify the ID in the PUT and DELETE routes.
HTTP is a really cool protocol for applying verbs (request methods) to nouns (URLs). In that spirit, it's probably best to use the request method to differentiate what you want to do to the resource that you're requesting.
Note: you can use the methodOverride middleware in express if you're worried about browsers not being able to use arbitrary HTTP methods.
The way the methodOverride middleware works is that you use an <input type="hidden" name="_method" value="PUT"> or similar to specify the method, despite it just being a regular POST request, and the methodOverride middleware will set the method property on the request that you get in your express application. This way, you can signal the intended request method without the client actually having to support that method.

Resources