alexr101 alexr101 - 1 month ago 6
Node.js Question

Express calling an api inside of a post request

I've hit a wall here, and can't really find a clear way of achieving this. I want to create a new video to add to my database. I get all the information from the view form, but a couple of the keys have to come from an api. So here's a basic example of what I have and need. What's a good way of achieving this?



router.post("/new", function(req, res){
var videoId = req.body.videoId;
var views = req.body.views;

//call the api with the video Id here somehow, and get title key for the video object below

//"www.api.com/"+videoId"

var video = {
title: title, //title from received from the api call
views: views
}

video.create(video, function(err, video){
//etc
})
});




Answer

You can use the http module built-in node to request the information from the API, otherwise request, which is probably more convenient to use.

Your code would then look like:

var request = require('request')

router.post("/new", function(req, res){
    var videoId = req.body.videoId;
    var views = req.body.views;

    //call the api with the video Id here somehow, and get title key for the video object below
    request.get('www.api.com/' + videoId, function(err, res) {


        var videoData = {
            title: res.title, //title from received from the api call
            views: res.views
        }

        video.create(videoData, function(err, video){
            //etc
        })
    })
});