11

我正在使用请求库进行外部 api 调用。https://github.com/request/request。我正在使用本机承诺/异步扩展。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 未定义。

4

2 回答 2

29

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

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

const options = {

        resolveWithFullResponse: true

}
于 2018-06-19T09:35:13.190 回答
2

我认为 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
    });
于 2018-06-19T09:29:09.937 回答