快速在邮件请求中调用api

时间:2016-11-03 15:32:51

标签: node.js express

我在这里碰到了一堵墙,无法真正找到实现这一目标的明确方法。我想创建一个新视频添加到我的数据库。我从视图表单中获取了所有信息,但是一些密钥必须来自api。所以这是我所拥有和需要的基本例子。实现这一目标的好方法是什么?

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
    })
});

1 个答案:

答案 0 :(得分:0)

您可以使用http模块内置节点从API请求信息,否则request,这可能更方便使用。

您的代码将如下所示:

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
        })
    })
});