在Nodejs中创建一个简单的oEmbed系统

时间:2014-05-30 13:05:07

标签: javascript node.js

对于个人项目,我尝试使用Nodejs创建一个简单的oEmbed系统。

我的路线如下:

app.get('/oembed/:url', function (req, res) {
    oembed.get(req.params.url, function (error, result) {
        return res.json(200, {message: "OK"});
    });
});
使用var oembed = require('../oembed');

公开

和oembed

对于oembed.js本身,我有:

var request = require('request');

exports.get = function(url, callback) {
    //this bit will be developed to call different functions depending on the URL
    html = vimeo(url)

};

function vimeo(url) {
    var videoUrl = url;
    var endpoint = 'http://www.vimeo.com/api/oembed.json';
    var url = endpoint + '?url=' + encodeURIComponent(videoUrl) + '&width=640';

    request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var video = JSON.parse(body);
          return video.html
        }
    })

}

到目前为止,vimeo函数会将所需的html返回给函数调用,但我在这里有点丢失。我不确定如何将html返回到初始请求(oembed.get部分)并使用回调的错误和结果参数。

非常感谢任何帮助(和建议)。

1 个答案:

答案 0 :(得分:0)

看来你只是不明白回调函数是如何工作的。在oembed.js文件中需要这样的内容:

var request = require('request');

exports.get = function(url, callback) {
    var endpoint = 'http://www.vimeo.com/api/oembed.json';

    request(endpoint + '?url=' + encodeURIComponent(url) + '&width=640', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            try {
                callback(null, JSON.parse(body).html);
            } catch (error) {
                callback(error);
            }
        }
    });
};

你的路线应该是这样的:

app.get('/oembed/:url', function (req, res) {
    oembed.get(req.params.url, function (error, result) {
        if (error) {
            res.json(500, {message: error});
        } else {
            res.json(200, {message: "OK"});
        }
    });
});