Skip to content

Instantly share code, notes, and snippets.

@AlphaNerd
Created May 29, 2019 13:33
Show Gist options
  • Save AlphaNerd/07b939eae212648c68611fcb0405fb1c to your computer and use it in GitHub Desktop.
Save AlphaNerd/07b939eae212648c68611fcb0405fb1c to your computer and use it in GitHub Desktop.
NodeJS Simple API and Request Example
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var request = require('request');
// configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 4000; // set our port
// ROUTES FOR OUR API
// =============================================================================
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
app.get('/', function(req, res) {
let p1 = new Promise(function(resolve,reject){
let url = `http://api.openweathermap.org/data/2.5/weather?q=moncton&units=metric&appid=5c196287722fc5d9f43aa3c91beb8e36`;
request(url,function(error,res,body){
if(!error){
console.log(body)
resolve(body)
}else{
reject(error)
}
})
})
let p2 = new Promise(function(resolve,reject){
let bcurl = 'https://api.bigcommerce.com/stores/####/v3/catalog/products';
let options = {
url: bcurl,
headers: {
"Accepts": "application/json",
"Content-Type": "application/json",
"X-Auth-Token": "################################",
"X-Auth-Client": "################################"
}
}
request(options, function(error,res,body){
if(!error){
console.log(body)
resolve(body)
}else{
reject(error)
}
})
})
Promise.all([p1,p2]).then(function(resp){
var data = {
moncton: JSON.parse(resp[0]),
smokem: JSON.parse(resp[1])
}
res.status(200).send(data)
})
});
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment