Skip to content

Instantly share code, notes, and snippets.

@ernestlv
Created March 23, 2018 16:48
Show Gist options
  • Save ernestlv/c931de4544a46f30e6e6e991ae164fa2 to your computer and use it in GitHub Desktop.
Save ernestlv/c931de4544a46f30e6e6e991ae164fa2 to your computer and use it in GitHub Desktop.
Proxy a REST/json request to an external API in Node.js
const http = require('http')
const httpS = require('https')
const Router = require('router')
const port = process.env.PORT || 3000
const router = Router()
router.get('/', (req, res) => {
res.write('REST API is up!');
res.end();
})
router.get('/test', (req, res) => {
console.log('calling pandora...')
httpS.get('https://api.nextbigsound.com/events/v1/entity/356?start=17167&end=17256&access_token=8c089170d31ea3b11f1ea65dbfc8ea46', (apiRes) => {
let data = '';
apiRes.on('data', (chunk) => {
console.log('processing pandora data...')
data += chunk
});
apiRes.on('end', () => {
console.log('dispatching pandora data...')
res.writeHead(200, {"Content-Type": "application/json"});
res.end(data);
});
}).on('error', e => {
console.log('Pandora API error', e);
});
})
const serverMain = (req, res) => {
router(req, res, (req, res) => {});
}
http.createServer(serverMain).listen(port);
console.log('REST API listen port '+port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment