Nodejs Request Promise 如何显示状态码

Nodejs Request Promise How to display status code

我正在使用请求库进行外部 api 调用。 https://github.com/request/request. I am using the native promise/async extention. https://github.com/request/request-promise-native.

但是我无法检查状态代码,它是未定义的。

public async session(): Promise<any> {

    const url = <removed>;

    const options = {

        uri: url,
        headers: {
            'Authorization': this.config.token
        },
        json: true,
        body: {
        }
    }

    try {
        const res = await request.post(options);

        if (res.statusCode !== 200) {
            // do something
        }
        console.log(res);
        console.log("statuscode", res.statusCode)
        return res;
    } catch (err) {
        return err;
    }
}

res.statusCode 未定义。

我认为 res 对象可能未定义。你可以尝试请求作为回调

request(options, function (error, response, body) {

  console.log('statusCode:', response && response.statusCode); 

});

或者你可以这样做 https://www.npmjs.com/package/request-promise

var options = {
    uri: 'http://the-server.com/will-return/404',
    simple: true,
    transform: function (body, response, resolveWithFullResponse) { /* ... */ }
};

rp(options)
    .catch(errors.StatusCodeError, function (reason) {
        // reason.response is the transformed response
    });

根据文档,我们需要在选项中定义我们想要 return 完整响应。

https://github.com/request/request-promise#get-the-full-response-instead-of-just-the-body

const options = {

        resolveWithFullResponse: true

}