【问题标题】:api request connection issue in nodejsnodejs中的api请求连接问题
【发布时间】:2022-01-04 14:04:13
【问题描述】:

我正在尝试使用基本身份验证向 Web url 发出获取请求。但它因连接问题而失败。

注意:当我使用 'request' 库而不是 'got' 时它可以工作

我在这里错过了什么?

const got = require('got');

(async () => {
  try {
    const res = await got( 
                      { 
                        url: 'https://httpbin.org/anything',
                        headers: {
                        Accept: 'application/json'
                       //Authorization: 'Basic abcjghgh8****'
                      }
                    })
    console.log('statusCode:', res.statusCode);
        console.log('body:', res.body);
    } catch (error) {
        console.log('error:', error);
    }
})();

输出:

图书馆

【问题讨论】:

    标签: javascript node.js api rest node.js-got


    【解决方案1】:

    在使用got() 时,如果您想要正文,则需要使用await got(...).json()await got(...).text() 或任何适合您的数据类型的选项。默认情况下,body 还没有被读取(有点像fetch() 接口,但是更容易使用,因为你可以直接使用.json() 方法)。

    const got = require('got');
    
    (async () => {
        try {
            const body = await got({
                url: 'some URL here',
                headers: {
                    Accept: 'application/json',
                    Authorization: 'Basic abcjghgh8****'
                }
            }).json(); // add .json() here
            console.log('body:', body);
        } catch (error) {
            console.log('error:', error);
        }
    })();
    

    而且,got().json() 直接解析为正文。

    您不必自己检查 statusCode,因为如果它不是 2xx 状态,那么它将自动拒绝承诺。

    【讨论】:

    • 我在更改后得到这个 (async () => { ^.TypeError: {(intermediate value)(intermediate value)(intermediate value)} is not a function
    • @itgeek - 好的,我修好了。您的代码中似乎有一个额外的},因为我所做的只是从您那里复制它。
    • }).json(); // 在此处添加 .json() ^ SyntaxError: Unexpected token ')'
    • @itgeek - 好吧,我正在演示您如何使用.json() 解决此问题,并且由于您没有提供实际 URL,因此我没有尝试运行代码。我假设您可以自己修复支撑语法错误,但我已经再次编辑了我的版本。从这里开始,您应该独自一人。
    • 感谢您的回复。语法不是这里的问题,我遇到了与您分享的第一个错误。 TypeError: {(intermediate value)(intermediate value)(intermediate value)} 不是函数
    猜你喜欢
    • 1970-01-01
    • 2011-06-06
    • 2020-06-22
    • 2020-02-20
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多