Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs Request Promise How to display status code

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.

like image 604
Kay Avatar asked Jun 19 '18 09:06

Kay


People also ask

How do you send a header in request promise?

var request = require('request-promise'); var uri = 'http://domain.name/'; var _include_headers = function(body, response, resolveWithFullResponse) { return {'headers': response. headers, 'data': body}; }; var options = { method: 'GET', uri: uri, json: true, transform: _include_headers, } return request(options) .

Is request promise deprecated?

This package is also deprecated because it depends on request . Fyi, here is the reasoning of request 's deprecation and a list of alternative libraries.

What is status in node JS?

status() function set the HTTP status for the response. It is a chainable alias of Node's response. statusCode. Parameter: This function accepts single parameter code that holds the HTTP status code.


1 Answers

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

}
like image 116
Kay Avatar answered Oct 11 '22 11:10

Kay