Nodejs Request Promise How to display status code

Kay picture Kay · Jun 19, 2018 · Viewed 15.7k times · Source

I am using the request library to make external api calls. https://github.com/request/request. I am using the native promise/async extention. https://github.com/request/request-promise-native.

However I am not able to check the status code, it is undefined.

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

The res.statusCode is undefined.

Answer

Kay picture Kay · Jun 19, 2018

According to the documentation we need to define in the options that we want to return the full response.

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

const options = {

        resolveWithFullResponse: true

}