Node.js 意外 token R

标签 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;
});

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

最佳答案

这里的问题是嬉皮士有时会期望 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/

相关文章:

node.js - 将每个用户的时间戳存储在已排序的 Redis 集合中

node.js - 使用额外的列进行多对多的序列化

node.js - Ffmpeg 将视频持续时间发送到客户端(使用 node-fluent-ffmpeg)

python - Airflow - 外部 API 调用给出 Negsignal.SIGSEGV 错误

c++ - Visual Studio "The debug worker process exited unexpectedly"每次运行都在同一个断点上

visual-studio - 停止执行我的程序并转到调试器而不设置断点(Visual Studio/GCC 和 C++)

debugging - 从 IntelliJ 调试功能测试

javascript - 在 Mongoose 中过滤过滤结果

api - Stripe : webhook events order

python - 用于在 Python 中过滤对象的用户界面