【发布时间】:2020-10-19 23:47:03
【问题描述】:
我正在尝试从 Node.js Expressjs 进行 API 调用。 API 调用工作正常,但是在解析对 JSON 的响应后,当我尝试访问不同的字段时,它给了我一个错误。 我尝试将 JSON 对象的一个元素的类型记录到控制台。首先它说对象,然后说取消定义(或者如果尝试记录内容本身,它会给我一个错误)。
var request = require('request');
const app = express();
//For serving static pages
// app.use(express.static('./static'))
app.get('/', (req, res) =>{
res.send('You have successfully contacted the API')
});
app.get('/:ticker', (req, res) => {
var requestOptions = {
'url': 'https://api.tiingo.com/tiingo/daily/' + req.params.ticker + '/prices?startDate=2019-01-02&token=74e7c9d22c2ffe8e9b5643edc2ef48bbddc6e69e',
'headers': {
'Content-Type': 'application/json'
}
};
request(requestOptions,
function(error, response, body) {
result = JSON.parse(body);
console.log('The type is ' + typeof (result[0].date)) //This statement prints different results twice
res.send(result);
}
);
});
app.listen(process.env.PORT || 3000)
终端说:
The type is string
D:\Web Dev Bootcamp\NodeJS-Tutorial\index.js:24
console.log('The type is ' + typeof (result[0].date))
^
TypeError: Cannot read property 'date' of undefined
at Request._callback (D:\Web Dev Bootcamp\NodeJS-Tutorial\index.js:24:60)
at Request.self.callback (D:\Web Dev Bootcamp\NodeJS-Tutorial\node_modules\request\request.js:185:22)
at Request.emit (events.js:314:20)
at Request.<anonymous> (D:\Web Dev Bootcamp\NodeJS-Tutorial\node_modules\request\request.js:1154:10)
at Request.emit (events.js:314:20)
at IncomingMessage.<anonymous> (D:\Web Dev Bootcamp\NodeJS-Tutorial\node_modules\request\request.js:1076:12)
at Object.onceWrapper (events.js:420:28)
at IncomingMessage.emit (events.js:326:22)
at endReadableNT (_stream_readable.js:1223:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21) [nodemon] app crashed - waiting for file changes before starting...
【问题讨论】:
-
看起来很明显,有时当你发出请求时,
result[0]是undefined所以result[0].date是一个 TypeError。您必须弄清楚为什么会这样,或者在尝试使用result和result[0]之前检查它们是否有效。由于您将req.params.ticker从一个请求更改为下一个请求,因此它可能不适用于某些股票代码值。 -
我建议您也将
console.log(req.params.ticker)添加到您的请求处理程序中,因为您可能会得到一个您不想要的值。例如,如果这来自浏览器,您可能会收到favicon.ico,因为您的app.get('/:ticker', ...)是一个通配符路由,它匹配发送到您的服务器的任何顶级请求。这通常是有问题的。 -
它不会在不同的调用上给我不同的结果,而是在“相同”的调用上给我不同的结果。它给出的第一个输出可能是因为飞行前 CORS 请求和第二次再次发出请求,如此处所述 [stackoverflow.com/questions/54957409/…
-
顺便说一句,request 包已于 8 个月前弃用
-
CORS 飞行前不针对 GET 请求,而是针对 OPTIONS 请求,所以我不确定您在说什么。只需向您的请求处理程序添加一堆调试,这样您就可以准确地看到您正在请求的 URL 以及您得到的确切响应。这是 BASIC 调试,只有您可以做并且需要在我们为您提供帮助之前完成。
标签: javascript node.js