RequestHook.onRequest Method
Handles a request before it is sent.
class TemplateRequestHook extends RequestHook {
async onRequest (event) {
// ...
}
}
The onRequest method’s event object exposes the following fields.
| Property | Type | Description |
|---|---|---|
event.requestOptions |
RequestOptions | Contains request parameters. You can use it to change request parameters before a request is sent. |
event.isAjax |
Boolean | Specifies if a request is performed using AJAX. |
async onRequest (event) {
if (event.isAjax) {
console.log(event.requestOptions.url);
console.log(event.requestOptions.credentials.username);
event.requestOptions.headers['custom-header'] = 'value';
}
}
RequestOptions
The RequestOptions object contains request parameters.
| Property | Type | Description |
|---|---|---|
headers |
Object | Request headers in the property-value form. |
body |
Buffer | The request body. |
url |
String | Read-only. The URL to which the request is sent. Refer to Change Request’s URL for details. |
protocol |
String | The protocol to use. Default: http:. |
hostname |
String | The alias for the host. |
host |
String | The domain name or IP address of the server to issue the request to. Default: localhost. |
port |
Number | The port of the remote server. Default: 80. |
path |
String | The request path. Should include query string if any. E.G. ‘/index.html?page=12’. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. Default: ‘/‘. |
method |
String | The string specifying the HTTP request method. Default: ‘GET’. |
credentials |
Object | Credentials to use for Windows (NTLM) or Basic authentication. HTTP Basic authentication requires a username and a password. NTLM authentication services may need to know your workstation and domain. See HTTP Authentication. |
proxy |
Object | If a proxy is used, the property contains information about its host, hostname, port, proxyAuth, authHeader, and bypassRules. |
Change Request’s URL
Since the RequestOptions URL parameter is read-only, you cannot use it to update the request’s URL. To change the URL, update the following RequestOptions parameters: protocol, host, hostname, port, path, and headers.
class CustomRequestHook extends RequestHook {
onRequest (e) {
e.requestOptions.protocol = 'https:';
e.requestOptions.host = 'devexpress.github.io';
e.requestOptions.hostname = 'devexpress.github.io';
e.requestOptions.port = '';
e.requestOptions.path = '/testcafe/example/thank-you.html';
e.requestOptions.headers['host'] = 'devexpress.github.io';
}
onResponse (responseEvent) {
}
}