javascript - Hide an API key (in an environment variable perhaps?) when using Angular -
i'm running small angular application node/express backend.
in 1 of angular factories (i.e. on client side) make $http request github return user info. however, github-generated key (which meant kept secret) required this.
i know can't use process.env.xyz on client side. i'm wondering how keep api key secret? have make request on end instead? if so, how transfer returned github data front end?
sorry if seems simplistic relative novice, clear responses code examples appreciated. thank you
unfortunately have proxy request on backend keep key secret. (i assuming need user data unavailable via unauthenticated request https://api.github.com/users/rsp?callback=foo because otherwise wouldn't need use api keys in first place - didn't need guess).
what can this: in backend can add new route frontend getting info. can whatever need - using or not secret api keys, verify request, process response before returning client etc.
example:
var app = require('express')(); app.get('/github-user/:user', function (req, res) { getuser(req.params.user, function (err, data) { if (err) res.json({error: "some error"}); else res.json(data); }); }); function getuser(user, callback) { // stub function should more if (!user) callback("error"); else callback(null, {user:user, name:"the user "+user}); } app.listen(3000, function () { console.log('listening on port 3000'); });
in example can user info at:
the function getuser
should make actual request github , before call can change if frontend making request e.g. cheching "referer" header or other things, validate input etc.
now, if need public info may able use public json-p api - example using jquery make things simple:
var user = prompt("user name:"); var req = $.getjson('https://api.github.com/users/'+user); req.then(function (data) { console.log(data); });
see demo
Comments
Post a Comment