Skip to content

Instantly share code, notes, and snippets.

@wmora
Last active May 11, 2020 22:51
Show Gist options
  • Save wmora/5087193 to your computer and use it in GitHub Desktop.
Save wmora/5087193 to your computer and use it in GitHub Desktop.
This is a basic example of a GET call to an https server using node.js + express
//It's an express app, so make sure you download the dependencies
var express = require('express')
, http = require('http')
, https = require('https')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 8888);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.configure('development', function () {
app.use(express.errorHandler());
});
//Assume the call will be to https://the.https.server/resource/24
//This function basically serves as a proxy for an external service.
//It returns the same response from the server for demo purposes.
var getCall = function(request, response) {
https.get("https://the.https.server/resource/" + request.params.resourceId, function(res) {
res.on("data", function(d) {
response.json(res.statusCode, JSON.parse(d.toString()));
});
res.on("error", function(e) {
response.json(res.statusCode, JSON.parse(e.toString()));
});
});
}
//URL mapping
app.get('/resource/:resourceId', getCall);
http.createServer(app).listen(app.get('port'), function () {
console.log("Mock server listening on port " + app.get('port'));
});
//And that's it! You should be able to test it making a call to your node server at http://localhost:8888/resources/<anId>
@prapakaransp
Copy link

Is there any extra step required for error handling. The full app gets crashed if no response from the server.

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