简体   繁体   English

nodejs中的api请求连接问题

[英]api request connection issue in nodejs

I'm trying to make a get request to a web url using basic auth.我正在尝试使用基本身份验证向 web url 发出获取请求。 But it failed with connection issues.但它因连接问题而失败。

Note: It works when i use 'request' library instead of 'got'注意:当我使用“请求”库而不是“得到”时它可以工作

What I'm I missing here?我在这里想念什么?

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);
    }
})();

OUTPUT: OUTPUT:

library图书馆

When using got() , if you want the body, then you need to use await got(...).json() or await got(...).text() or whatever option is appropriate to your data type.使用got()时,如果您想要正文,则需要使用await got(...).json()await got(...).text()或任何适合您的数据类型的选项。 By default, the body has not yet been read (somewhat like the fetch() interface, but easier to use because you can just directly use the .json() method).默认情况下,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);
    }
})();

And, got().json() resolves directly to the body.而且, got().json()直接解析为正文。

You don't have to check the statusCode yourself because if it isn't a 2xx status, then it will reject the promise automatically.您不必自己检查 statusCode,因为如果它不是 2xx 状态,那么它将自动拒绝 promise。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM