错误400:必需参数部分

时间:2017-02-20 17:50:51

标签: javascript node.js youtube-api youtube-data-api

Iam尝试使用youtube api使用youtube api查找有关特定视频的信息。我使用https模块发送和接收数据

这是我用过的代码

 var youtube_query=querystring.stringify({

 q:'bangarang',
 key:'api_key',
 part:'snippet'

});


var options_you = {                     

  host:'www.googleapis.com',

  method:'GET',

  path:'/youtube/v3/search'

};


function getvid_id(vid_result){  
                                              //callback function for finding the information on the video 
      vid_result.setEncoding('utf8');
      console.log("STATUS :"+vid_result.statusCode);//to show the status code

      vid_result.on('data', function (body) {

    console.log(body);
    });      
}

var youtube_request = https.request(options_you,getvid_id);

youtube_request.on('error', function(e) {


console.log('problem with request: ' + e.message);
    });

    youtube_request.write(youtube_query);
        youtube_request.end();

但是我得到以下回复

STATUS :400
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required parameter: part",
    "locationType": "parameter",
    "location": "part"
   }
  ],
  "code": 400,
  "message": "Required parameter: part"
 }
}

正如您所看到的,我已经提供了part参数。但是我找不到它无法正常工作的原因。

1 个答案:

答案 0 :(得分:1)

您可以将查询字符串直接传递给path字段:

var querystring = require("querystring");
var https = require("https");

var youtube_query = querystring.stringify({
    q: 'bangarang',
    key: 'api_key',
    part: 'snippet'
});

var options_you = {
    host: 'www.googleapis.com',
    method: 'GET',
    path: '/youtube/v3/search?' + youtube_query
};

var youtube_request = https.request(options_you, function(res) {
    res.on('data', function(d) {
        process.stdout.write(d);
    });
});

youtube_request.end();