How to create a simple Node.js proxy for third-party APIs
Illarion Khapyorskiy @illarionvk
How to create a simple Node.js proxy for third-party APIs
Illarion Khapyorskiy @illarionvk
JSONP | Proxy with CORS policy |
---|---|
Only GET | GET, POST, PUT, DELETE |
Results are injected as code (possible XSS issues) |
Results are parsed (more secure) |
Indirect error handling | Reliable error handling |
A stable and reliable application framework for Node.js, used in production by Walmart, Yahoo and NPM.
Created by Eran Hammer
1 var url = require('url');
2
3 var Hapi = require('hapi');
4
5 var Wreck = require('wreck'); // HTTP Client Utilities
1 var server = new Hapi.Server();
2
3 server.connection({
4 port: process.env.PORT || 3000
5 });
1 server.method('getInstagram', getInstagram, {
2 cache: {
3 expiresIn: 60 * 60 * 1000,
4 staleIn: 60 * 1000,
5 staleTimeout: 100
6 }
7 });
1 var getInstagram = function(next) {
2 var instagramURL = 'https://api.instagram.com/...';
3 Wreck.get(instagramURL, null, function(err, res, payload) {
4 if (err) { return next(err); }
5 if (res.statusCode !== 200) {
6 return next(res.statusCode);
7 }
8 return next(null, JSON.parse(payload));
9 });
10 };
1 server.route({ method: 'GET', path: '/instagram.json',
2 handler: function(request, reply) {
3 return server.methods.getInstagram( function(error, result) {
4 if (error) { return reply({ error: error }).code(500); }
5 return reply(result);
6 });
7 }, config: {
8 cors: true,
9 cache: { expiresIn: 60 * 60 * 1000, privacy: 'private' }
10 }
11 });
1 server.start( function() {
2 console.log('Server running at:', server.info.uri);
3 });