Nodejs Request Promise How to display status code
Asked Answered
W

2

13

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.

Wendell answered 19/6, 2018 at 9:21 Comment(6)
can you post the full codeFlatways
@NuOneTAttygalle What detail are you missing, i have redacted the url but that shouldint be an issue.Wendell
Can you dump whole res object? I want to see what response are you getting from service? Is it undefined or there is any other issue.Seyler
@Seyler i get a single object, i have removed one field which incldued a session token but this is pretty much it. pastebin.com/EFzE6NhBWendell
can you show me how you calling this?Gynandry
Ive already solved this now, see my answer.Wendell
W
31

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

}
Wendell answered 19/6, 2018 at 9:35 Comment(3)
I've moved away from this library and started to use axios instead.Wendell
does Axios has resolveWithFullResponse?Impressionist
axios returns a schema that includes the status code: axios-http.com/docs/res_schemaDiplomatic
F
2

I think res object might undefined. you can try request as callback

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

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

});

or you can do like this 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
    });
Flatways answered 19/6, 2018 at 9:29 Comment(1)
I need to return a promise. Thats . the whole reason for using the promise-native library. The respone is not undefined it contains a object with the correct fields. but there is just no respones codesWendell

© 2022 - 2024 — McMap. All rights reserved.