I am just starting out learning node.js after deciding to write my next API using node and restify. There will only be a couple of users accessing the API and it will be a strictly private one - no one else should be able to access it.
Basically, I need away to check that "key" and "pass" params are supplied (and valid) for every request. So, I thought I could add some middleware that is executed before everything else to do the checking.. e.g.:
var restify = require('restify');
var server = restify.createServer({
name: 'test'
});
server.use(function(req, res, next) {
if (req.params.key == null) {
console.log("No API key supplied");
return next(new restify.NotAuthorizedError("No API key supplied"));
}
});
server.use(restify.bodyParser());
server.listen(8888, function() {
console.log('%s listening at %s', server.name, server.url);
});
server.get('/test', function(req, res, next) {
res.send('Hello World');
return next();
});
Browsing to localhost:8888/test gives {"code":"NotAuthorized","message":"No API key supplied"} which is what I want.
However, browsing to http://localhost:8888/test?key=a still gives the same message..
Clearly, I'm not going about this the right way. Can someone point me in the right direction?
Thanks in advance.
I needed to add restify.queryParser() to parse the GET params. Now, this works:
var restify = require('restify');
var server = restify.createServer({
name: 'test'
});
server.use(restify.queryParser());
server.use(restify.bodyParser());
server.use(function(req, res, next) {
if (req.query.key == null) {
console.log("No API key supplied");
return next(new restify.NotAuthorizedError("No API key supplied"));
} else return next();
});
server.listen(8888, function() {
console.log('%s listening at %s', server.name, server.url);
});
server.get('/test', function(req, res, next) {
res.send('Hello World');
return next();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With