node.js - 如何从请求中获取变量(url,function(错误,响应,正文){var getME})?

时间:2017-11-26 18:08:18

标签: javascript node.js require

我使用的代码没有参数/填充: https://www.npmjs.com/package/request

    var request = require('request');
    request('http://www.google.com', function (error, response, body) {
        console.log('error:', error); // Print the error if one occurred
        console.log('statusCode:', response && response.statusCode); 
        // Print the response status code if a response was received
        console.log('body:', body); // Print the HTML for the Google homepage.
    });

我的代码:

    const YTAPIVideoURL = ('https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=' + Channel_ID + '&eventType=live&type=video&key=' + YT_API_KEY);

    const YTAPIStatusURL = ('https://www.googleapis.com/youtube/v3/liveBroadcasts?part=id%2Csnippet%2Cstatus&mine=true&broadcastStatus=active&key='+YT_API_KEY);


    var livestreamStatus = true;
    if (livestreamStatus == true) {
        var VIDEO_ID = "";
        var VIDEO_TITLE = "";

    // request options
        const APIoptions = {
            url: YTAPIVideoURL,
            method: "GET",
            timeout: 10000,
            followRedirect: true,
            maxRedirects: 10
        };

     //Request
        const APIrequest = request(APIoptions,
        function(error, response, body) {
            if (!error && response.statusCode == 200) {
                var jsonContent = JSON.parse(body);
                console.log("jsonContent: " + jsonContent);
                console.log("parsed info: " + jsonContent["items"][0]["id"]["videoId"]);
                if ((jsonContent["items"][0]) != [""]) {
                    VIDEO_TITLE = jsonContent["items"][0]["snippet"]["title"];
                    VIDEO_ID = jsonContent["items"][0]["id"]["videoId"];

                    console.log(VIDEO_ID) //THIS IS THE DATA I NEED

                } else {
                    videoId = false;
                    VIDEO_TITLE = false;
                }
                /*console.log(videoId);*/
            } else {
                console.log('error' + response.statusCode);
            }
        });
        console.log(VIDEO_ID); //THIS IS WHERE I NEED THE DATA

我需要从require函数中检索VIDEO_ID ...我已经搜索过并且遇到了很多麻烦,因为所有的解决方案只是满足于使用console.log()来打印出来来自require对象| module ..

的数据

我想要的数据被抓取并放入var VIDEO_ID并在行上显示; console.log("parsed info: " + jsonContent["items"][0]["id"]console.log(VIDEO_ID) //THIS IS THE DATA I NEED 这些行记录了我需要的数据。

我需要在此处的函数外部访问VIDEO_ID:console.log(VIDEO_ID); //THIS IS WHERE I NEED THE DATA 我知道有require.XXXX(APIoptions, callback)这样的函数,但我不知道回调是什么,我应该使用哪一个..帮助请吗?

0 个答案:

没有答案