-
Notifications
You must be signed in to change notification settings - Fork 11
/
fetch-use-token.js
42 lines (38 loc) · 1.7 KB
/
fetch-use-token.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
async function testPage(page) {
await page.setRequestInterception(true);
// Intercept the next request, change its method to POST and add the request body
page.once("request", async interceptedRequest => {
interceptedRequest.continue({
method: "POST",
postData: '{"username": "exampleUser","password": "examplePassword"}',
headers: { ...interceptedRequest.headers(), "content-type": "application/json" }
});
});
// Sending first request to get token
const response = await page.goto("https://private-xxxxx.apiary-mock.com/authenticate");
bodyJSON = await response.json();
// response.text() prints out the response body as a string, useful if you're not using JSON
// response.json() parses the response body JSON and throws an error if it isn't valid JSON
console.log({
url: response.url(),
statusCode: response.status(),
body: await response.text(),
bodyJSON
});
// Intercept the next request, change its method to POST and add the request body using the response we got from the first request
page.once("request", async interceptedRequest => {
interceptedRequest.continue({
method: "POST",
postData: { "token": "\${bodyJSON.token}" },
headers: { ...interceptedRequest.headers(), "content-type": "application/json" }
});
});
// Sending second request using info from the first response
const result = await page.goto("https://private-xxxxx.apiary-mock.com/exampleSecureEndpoint");
console.log({
url: result.url(),
statusCode: result.status(),
body: await result.text()
});
}
module.exports = testPage;