1

I am new to Node/Express and to API's in general. Long story short, I am a front end guy diving into backend and architecture for the first time. The breakdown of my problem is as follows:

App description: A web app that allows users to view medical data records.

Desired feature: Change the state of a json record on page load. When a user opens a record(page), I want to change a json object from UNDIAGNOSED to DIAGNOSED automatically. This needs to be done server side to avoid exposing the api endpoint, which needs to stay hidden for security reasons. Think of it like a 'read/unread' email. Once it has been opened, it changes the state to 'read'

Probelem: ...I am a newb...

//When the server GETs a request to this URL
router.get('/content/:contentid', function(req, res, next) {

// Configure the REST platform call
var platform_options = {
    resource: '/content/' + req.params.contentid,
    method: 'POST',
    json: "diagnosis_state: DIAGNOSED"
};

// Make the call
var platform = ihplatform(_config, req.session, platform_options, callback);
platform.execute();

// Result processing
function callback(error, response, body) {
    console.log(response.body);
}

});

I am using a custom HTTP API that was built in-house by another developer. The endpoint for the call is dynamically generated via the re.params.contentid. You will also notice that the call itself is built into the platform.execute function.

There is a bit of copy/pasting going on, as I am trying to modify a working call.

My question is this: How do I make an api POST call to a remote API upon the HTTP request for a certain url via express.js?

4
  • What exactly is your question? Do you know what back-end API you call from your server to change the state to diagnosed and do you have a Javascript library for that API or is it an http API? It's kind of like you've ask us how to drive to a destination two hours away, but you didn't tell us where you wanted to go or where you are now. Commented Oct 20, 2014 at 22:47
  • Question edited to answer your questions. Thank you! Commented Oct 20, 2014 at 23:31
  • 1
    If ihplatform() and platform.execute() will make the custom API call for you and call your callback function when it's done, what else are you asking about? Commented Oct 20, 2014 at 23:39
  • Express is for receiving HTTP traffic and responding to it, not initiating it. Put another way, it's a web server, not a web (HTTP) client. Commented Oct 21, 2014 at 13:45

3 Answers 3

1

Here is what you can do on express.js -

1) write a module for route mappings in a separate js file where all the mappings can be listed. Below is the code snippet of the module file

function mappings(app)
    {
        var email = require('./routes/emails');// ./routes/emails is js file location exporting UpdateEmail variable which contains function for update
        app.put('/email/update', email.UpdateEmail); // mapping url /email/update to exported variable UpdateEmail
    }

2) add following statement in app.js file where mapRoutes is a .js file created in step 1

require('./mapRoutes').mappings(app);

3) Below is the sample app.js file

var path = require('path');

var favicon = require('static-favicon');

var logger = require('morgan');

var cookieParser = require('cookie-parser');

var bodyParser = require('body-parser');


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));

app.set('view engine', 'jade');

app.use(favicon());

app.use(logger('dev'));

app.use(bodyParser.json());

app.use(bodyParser.urlencoded());

app.use(cookieParser());

app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

app.use('/users', users);

app.all('*', function(req, res, next) {

  res.header('Access-Control-Allow-Origin', req.headers.origin);

    res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');

    res.header('Access-Control-Allow-Credentials', false);

    res.header('Access-Control-Max-Age', '86400');

    res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');

  next();

 });
app.options('*', function(req, res) {
   
 res.send(200);

});

require('./mapRoutes').mappings(app);

/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {

    var err = new Error('Not Found');

    err.status = 404;

    next(err);

});


/// error handlers

// development error handler

// will print stacktrace
if (app.get('env') === 'development') {

    app.use(function(err, req, res, next) {

        res.status(err.status || 500);

        res.render('error', {

            message: err.message,

            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {

    res.status(err.status || 500);

    res.render('error', {

        message: err.message,

        error: {}

    });

});



module.exports = app;

4) live website running on above code - kidslaughs.com

Sign up to request clarification or add additional context in comments.

Comments

0

I'm not quite sure your question here, because "POSTing from ExpressJS" could mean two different things.

In the most common case, you are making a POST request from a web page. While this might be served or even rendered via Express, the call is originating from the web page. In that case the javascript on the web page is making the post. Common web frameworks for that might be jQuery's $.ajax or Angular's $http. Whatever framework you use, you'll define the data to post, the API endpoint to post to, and what to do with the response.

Another meaning of your question might be that you want your Express app to make a http request from the server side. You will need a package to do so, so that you can make a HTTP programatically. A popular package for this is request.

It's hard to say more without knowing what frameworks you are working with. Keep searching around, you'll figure it out!

Comments

0

I think you're looking for request.js.

var request = require('request');
request.post('/content/' + req.params.contentid').form({json: "diagnosis_state: DIAGNOSED"})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.