Skip to content

Commit

Permalink
Merge b6fd7c4 into 52de13b
Browse files Browse the repository at this point in the history
  • Loading branch information
Giotino committed Sep 18, 2020
2 parents 52de13b + b6fd7c4 commit 8fbfb16
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
19 changes: 19 additions & 0 deletions readme.md
Expand Up @@ -740,6 +740,25 @@ Default: `[]`

Called with [normalized](source/core/index.ts) [request options](#options). Got will make no further changes to the request before it is sent. This is especially useful in conjunction with [`got.extend()`](#instances) when you want to create an API client that, for example, uses HMAC-signing.

**Note:** Changing `options.json` or `options.form` has no effect on the request, you should change `options.body` and, if needed, update the `options.headers` accordingly.\
Example:

```js
const got = require('got');

got.post({
json: {payload: 'old'},
hooks: {
beforeRequest: [
options => {
options.body = JSON.stringify({payload: 'new'});
options.headers['content-length'] = options.body.length.toString();
}
]
}
});
```

**Tip:** You can override the `request` function by returning a [`ClientRequest`-like](https://nodejs.org/api/http.html#http_class_http_clientrequest) instance or a [`IncomingMessage`-like](https://nodejs.org/api/http.html#http_class_http_incomingmessage) instance. This is very useful when creating a custom cache mechanism.

###### hooks.beforeRedirect
Expand Down
4 changes: 4 additions & 0 deletions source/core/index.ts
Expand Up @@ -2308,6 +2308,10 @@ export default class Request extends Duplex implements RequestEvents<Request> {
}
}

if (options.body && this[kBody] !== options.body) {
this[kBody] = options.body;
}

const {agent, request, timeout, url} = options;

if (options.dnsCache && !('lookup' in options)) {
Expand Down
22 changes: 22 additions & 0 deletions test/hooks.ts
Expand Up @@ -17,6 +17,10 @@ const echoHeaders: Handler = (request, response) => {
response.end(JSON.stringify(request.headers));
};

const echoBody: Handler = async (request, response) => {
response.end(await getStream(request));
};

const echoUrl: Handler = (request, response) => {
response.end(request.url);
};
Expand Down Expand Up @@ -1194,3 +1198,21 @@ test('no duplicate hook calls when returning original request options', withServ
t.is(beforeHookCount, 4);
t.is(afterHookCount, 4);
});

test('`beforeRequest` change body', withServer, async (t, server, got) => {
server.post('/', echoBody);

const response = await got.post({
json: {payload: 'old'},
hooks: {
beforeRequest: [
options => {
options.body = JSON.stringify({payload: 'new'});
options.headers['content-length'] = options.body.length.toString();
}
]
}
});

t.is(JSON.parse(response.body).payload, 'new');
});

0 comments on commit 8fbfb16

Please sign in to comment.