Got: On `afterResponse` token renewal, chained `.text()`|`.json()`|`.buffer()` method returns the wrong body

Created on 12 Mar 2020  Â·  4Comments  Â·  Source: sindresorhus/got

Describe the bug

  • Node.js version: 12.16.1
  • OS & version: MacOS Catalina

Given a client Got instance with a afterResponse hook to set/renew OAuth2 token upon 401 response.statusCode

const unchained = await client(url, options)
// unchained.body holds the correct (as a string) json result (i.e. after token properly set)

const chained = await client(url, options).json()
// chained is the json result of the 401 response (i.e. before token is properly set)

Actual behavior

When .json() is chained with a got instance with an afterResponse hook, it returns the json result of the first request and ignores (or overwrites?) the result of the second (and valid) request.

Expected behavior

When .json() is chained with a got instance with an afterResponse hook, it should return the json result of the last request.

Code to reproduce

Add the following to test\hooks.ts and run npx tsc && npx ava test/hooks.ts

test('afterResponse with retry as correct .json()', withServer, async (t, server, got) => {
    server.get('/', (request, response) => {
        if (request.headers.token !== 'unicorn') {
            response.statusCode = 401;
            response.end(JSON.stringify({hello: 'nasty'}));
        } else {
            response.end(JSON.stringify({hello: 'world'}));
        }
    });

    const body = await got({
        hooks: {
            afterResponse: [
                (response, retryWithMergedOptions) => {
                    if (response.statusCode === 401) {
                        return retryWithMergedOptions({
                            headers: {
                                token: 'unicorn'
                            }
                        });
                    }

                    return response;
                }
            ]
        }
    }).json() as any;
    t.is(body.hello, 'world');
});

Checklist

  • [x] I have read the documentation.
  • [x] I have tried my code with the latest version of Node.js and Got.
bug ✭ help wanted ✭

Most helpful comment

I added test cases for .text() and .buffer() methods for they are also affected.

All 4 comments

I opened a PR with the (currently failing) test to reproduce this issue.

Thank you for the report, I'll get back to this ASAP.

I added test cases for .text() and .buffer() methods for they are also affected.

Fixed in 99d70df02f209ffac80a6529001e63b8684056af

Was this page helpful?
0 / 5 - 0 ratings

Related issues

quocnguyen picture quocnguyen  Â·  4Comments

joolfe picture joolfe  Â·  3Comments

dAnjou picture dAnjou  Â·  3Comments

erfanium picture erfanium  Â·  3Comments

astoilkov picture astoilkov  Â·  3Comments