Skip to content

Instantly share code, notes, and snippets.

@camshaft
Last active May 21, 2021 09:08
Show Gist options
  • Save camshaft/4688223 to your computer and use it in GitHub Desktop.
Save camshaft/4688223 to your computer and use it in GitHub Desktop.
Superagent Middleware
/**
* Module dependencies
*/
var request = require("superagent");
/**
* Middleware to sign the request
*/
var authorizeRequest = function(token) {
// This will be called on the request
return function authorizeRequest(req, next) {
req.headers.authorization = "Bearer "+token;
// This will be called on the response
next(null, function (res, nextRes) {
nextRes();
});
}
};
/**
* Make the request
*/
request
.get("/api")
.use(signrequest("this-is-a-secret"))
.end(function(err, res){
console.log(res.body)
});
@timshadel
Copy link

Awesome! I'll bet that use can be put on plain http, and you could substitute sign request with authorize request, and then it would be generic.

@camshaft
Copy link
Author

camshaft commented Feb 1, 2013

how bout now?

@christiaanwesterbeek
Copy link

.use(signrequest("this-is-a-secret"))

should have been this right?

.use(authorizeRequest("this-is-a-secret"))

@robertu7
Copy link

robertu7 commented Dec 9, 2015

here is the simpler way:

var authorizeRequest = function(token) {

  // This will be called on the request
  return function authorizeRequest(req) {

    req.header.authorization = "Bearer " + token;

    return req;
  }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment