Skip to content

On afterResponse token renewal, chained .text()|.json()|.buffer() method returns the wrong body #1120

@PopGoesTheWza

Description

@PopGoesTheWza

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

  • I have read the documentation.
  • I have tried my code with the latest version of Node.js and Got.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions