Node.js意外令牌R.

时间:2014-02-10 19:06:45

标签: node.js api debugging testing

我从终端收到此错误:

SyntaxError: Unexpected token R
at Object.parse (native)
at Client.exports.json [as parse]   (/Users/terrychen/Desktop/Git/ControlPanel/node_modules/hippie/lib/hippie/parsers.js:15:18)
at Request._callback (/Users/terrychen/Desktop/Git/ControlPanel/node_modules/hippie/lib/hippie/client.js:388:10)
at Request.self.callback (/Users/terrychen/Desktop/Git/ControlPanel/node_modules/hippie/node_modules/request/request.js:129:22)
at Request.EventEmitter.emit (events.js:98:17)
at Request.<anonymous> (/Users/terrychen/Desktop/Git/ControlPanel/node_modules/hippie/node_modules/request/request.js:873:14)
at Request.EventEmitter.emit (events.js:117:20)
at IncomingMessage.<anonymous> (/Users/terrychen/Desktop/Git/ControlPanel/node_modules/hippie/node_modules/request/request.js:824:12)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16

虽然我只是用hippie API测试模块执行一个简单的脚本:

var hippie = require('hippie');

hippie()
.json().get('https://api.github.com/users/vesln')
.expectStatus(200)
.end(function(err, res, body) {
  if (err) throw err;
});

知道为什么会这样吗?感谢您的回答!

1 个答案:

答案 0 :(得分:3)

这里的问题是,在某些时候,hippie希望API返回要解析的JSON。您可能手动检查了该URL并看到它是JSON。但是这种类型的错误表明JSON.parse输入不良。通常,当unexpected token u传入时,您会看到undefined。 调试的第一步是将console.log(arguments)放在if(err..之前,而实际上只对res对象的内容感兴趣,它显示GitHub实际上在这里返回了一个错误。

{
...,
body: 'Request forbidden by administrative rules. Please make sure your request has a User-Agent header (http://developer.github.com/v3/#user-agent-required). Check https://developer.github.com for other possible causes.' }
}

这是意外令牌的R,这是无效的JSON。正如消息所述,丢失的User-Agent标题是最有可能的原因。

此代码有效。

var hippie = require('hippie');

hippie()
.header("user-agent", "derpbot")
.json().get('https://api.github.com/users/vesln')
.expectStatus(200)
.end(function(err, res, body) {
  if (err) throw err;
});