意外地使用了NodeJs

时间:2016-11-26 16:40:25

标签: javascript json ajax node.js npm

我对forecast.io的http请求有问题, 如果通常使用 $。ajax 调用请求,它的效果很好,如果我用ajax-request模块调用请求,则会给出输出:

SyntaxError: Unexpected token u in JSON at position 0
    at Object.parse (native)
    at ClientRequest.<anonymous> (/Users/rawnly/Documents/Github/weather/forecast.js:11:21)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at Socket.socketOnEnd (_http_client.js:346:9)
    at emitNone (events.js:91:20)
    at Socket.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)

此处为代码

const request = require('ajax-request');
const token = "**********";
const chalk = require('chalk');

request({
  url: `https://api.darksky.net/forecast/5884bb7f746da897d43f2189e5f3221a/49,12`,
  method: "GET",
  data: {
     format: "json"
  },
}, function(err, res, body) {
  if ( err ) {
    console.log( chalk.red(err) );
  }
  if ( res ) {
    console.log( chalk.red(res) );
  }

  if ( body !== undefined ) {
    var data = body ? JSON.parse(body) : body;
    console.log(data); // the output is undefined... :(
  }
});

提前感谢您的帮助。

编辑:错误输出=&gt; Error: socket hang up

在标记为重复之前

我很容易看到this问题和其他问题,但不起作用......

1 个答案:

答案 0 :(得分:0)

解决方案:根据@Aurora0001的建议,我尝试使用another library,但效果很好。