【问题标题】:JS https request returning undefined ResponseJS https 请求返回未定义的响应
【发布时间】:2021-07-08 12:22:49
【问题描述】:

我正在尝试从我的 JavaScript 应用程序向另一个应用程序中的端点进行 API 调用。

当我调用端点时,我会得到状态代码和消息,但我无法以任何方式访问响应正文。我尝试了不同的方法来获取数据,但似乎没有什么对我有用。

在“someAction”方法中,我想使用 API 调用的响应/结果中的数据。我在代码中添加了单个日志行打印的输出。

如何在定义“result.status/message”时未定义“result”?

为了将数据/正文获取为 JSON 或字符串,我需要做什么?

API 本身经过测试,并在 postman 中测试时返回数据。

感谢您的帮助!

const request   = require('request')

let callEndpoint = () => {
    return new Promise((resolve, reject) => {

        const url = `https://my.api.com/endpoint`

        const requestOptions = {
            url: url,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
                'My-API-Authorization': '123456789'
            },
            json: true,
            strictSSL: false
        }

        request.get(requestOptions, (err, response) => {
            if(err)
            {
                return reject(err);
            }
            return resolve(response);
        });
    });
}

let someAction = () => {
    callEndpoint()
        .then(result => {
            logger.logInfo(result.statusCode)           // => 200
            logger.logInfo(result.statusMessage)        // => OK
            logger.logInfo(result)                      // => undefined
            logger.logInfo(result.toString())           // => [object Object]
            logger.logInfo(result.body)                 // => undefined
            logger.logInfo(result.data)                 // => undefined

            JSON.parse(result.toString())               // => Unexpected token o in JSON at position 1    
            JSON.parse(result)                          // => Unexpected token o in JSON at position 1

            // DO SOME STUFF WITH THE RESULT
        })
}

【问题讨论】:

  • 您收到了回复,只是其中没有任何数据。因此,您对 API 的调用丢失了某些内容,或者您​​的 API 失败,但仍然返回没有数据的成功响应。
  • The request module is deprecated。不要使用它。
  • NodeJS 内置了库。这是 HTTPS => nodejs.org/api/https.html 和 HTTP => nodejs.org/api/http.html 的文档
  • @daddygames 我使用 Postman 测试了 API,并在那里获取了数据。这很奇怪。
  • 根据我们掌握的信息,很难说问题出在哪里。问题可能是已弃用的库,但我们无法确定。

标签: javascript node.js json https request


【解决方案1】:

使用 axios

而不是使用 request

link for axios

如果 Axios 无法正常工作,请检查您的 API

【讨论】:

  • 切换到不同的库如何解决问题?
  • 如您所见,request 是一个旧包,多年未更新,因此 Axios 将是一个不错的选择。
猜你喜欢
  • 2020-06-01
  • 2019-06-22
  • 2018-08-09
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-13
相关资源
最近更新 更多