节点“请求”方法不执行

时间:2015-11-22 14:54:42

标签: node.js header request

我的代码试图执行我的request方法,但它不会在那里。我正确设置了我的对象,但是我记录的内容没有被执行。我的设置不正确吗?

req = require("request");

var headers = {
    "Content-Type": "json/application",
    "Authorization": "M6V9Jt2HJa8bcYCjd1xItrVaw1dcHDEY5FRpxdfojhI"
}

var options = {
    url: "'http://api.nytimes.com/svc/topstories/v1/home.json?api-key="+NYTIMESKEY,
    method: 'GET',
    headers: headers
}

for(var i = 0; i < parsed.results.length; i++){

    abstracts.push(parsed.results[i].abstract);


    var url = formatUrl(abst, "https://api.datamarket.azure.com/data.ashx/amla/text-analytics/v1/GetSentiment?Text=");

            var sentStr = '';
            console.log("in there");
            req(options, function(error, response, body){
                if (!error && response.statusCode == 200){
                    console.log(body);
                    console.log("executing thing");
                }
            });

}

1 个答案:

答案 0 :(得分:1)

  1. 首先,您的选项对象中有印刷错误。

      

    var options = {      url:“'http://api.nytimes.com/svc/topstories/v1/home.json?api key =”+ NYTIMESKEY,

  2. “url”param有额外的单引号。当您尝试使用当前URL调用req函数时,您将收到“类型错误”(协议无效)。

    1. 其次,你的函数没有调用的原因,可能是空的parsed.results数组。我简化了你的代码。现在调用req函数。
    2. req = require("request");
      
      var headers = {
          "Content-Type": "json/application",
          "Authorization": "M6V9Jt2HJa8bcYCjd1xItrVaw1dcHDEY5FRpxdfojhI"
      }
      
      var options = {
          url: "http://api.nytimes.com/svc/topstories/v1/home.json?api-key=" + "something_you_nedd",
          method: 'GET',
          headers: headers
      }
      
      var sentStr = '';
      console.log("in there");
      req(options, function(error, response, body){
          console.log("on answer");
          if (!error && response.statusCode == 200){
              console.log(body);
              console.log("executing thing");
          }
      });