我从我的终端收到这个错误:
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;
});
知道为什么会这样吗?感谢您的回答!
最佳答案
这里的问题是嬉皮士有时会期望 API 返回 JSON 进行解析。您可能手动检查了该 URL 并发现它是 JSON。但这种类型的错误表明 JSON.parse
的输入有误。当传入 undefined
时,您通常会看到 unexpected token u
。
我采取的调试的第一步是将 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
header 。
此代码有效。
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;
});
关于Node.js 意外 token R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21685748/