Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

fix(basic): forward `proxyUrl` from `sendRequest` to the HTTP client (#4267)

Jay Hemnani60c131e61e67
diff --git a/docs/guides/got-scraping.mdx b/docs/guides/got-scraping.mdx
deleted file mode 100644
index a67967210..000000000
--- a/docs/guides/got-scraping.mdx
+++ /dev/null
@@ -1,190 +0,0 @@
----
-id: got-scraping
-title: Got Scraping
-description: Blazing fast cURL alternative for modern web scraping
----
-
-## Intro
-
-When using `BasicCrawler`, we have to send the requests manually. In order to do this, we can use the context-aware `sendRequest()` function:
-
-```ts
-import { BasicCrawler } from 'crawlee';
-
-const crawler = new BasicCrawler({
- async requestHandler({ sendRequest, log }) {
- const res = await sendRequest();
- log.info('received body', res.body);
- },
-});
-```
-
-It uses [`got-scraping`](https://github.com/apify/got-scraping) under the hood.
-Got Scraping is a [Got](https://github.com/sindresorhus/got) extension developed to mimic browser requests, so there's a high chance we'll open the webpage without getting blocked.
-
-## `sendRequest` API
-
-```ts
-async sendRequest(overrideOptions?: GotOptionsInit) => {
- return gotScraping({
- url: request.url,
- method: request.method,
- body: request.payload,
- headers: request.headers,
- proxyUrl: crawlingContext.proxyInfo?.url,
- sessionToken: session,
- responseType: 'text',
- ...overrideOptions,
- retry: {
- limit: 0,
- ...overrideOptions?.retry,
- },
- cookieJar: {
- getCookieString: (url: string) => session!.getCookieString(url),
- setCookie: (rawCookie: string, url: string) => session!.setCookie(rawCookie, url),
- ...overrideOptions?.cookieJar,
- },
- });
-}
-```
-
-### `url`
-
-By default, it's the URL of current task. However you can override this with a `string` or a `URL` instance if necessary.
-
-*More details in [Got documentation](https://github.com/sindresorhus/got/blob/main/documentation/2-options.md#url).*
-
-### `method`
-
-By default, it's the HTTP method of current task. Possible values are `'GET', 'POST', 'HEAD', 'PUT', 'PATCH', 'DELETE'`.
-
-*More details in [Got documentation](https://github.com/sindresorhus/got/blob/main/documentation/2-options.md#method).*
-
-### `body`
-
-By default, it's the HTTP payload of current task.
-
-*More details in [Got documentation](https://github.com/sindresorhus/got/blob/main/documentation/2-options.md#body).*
-
-### `headers`
-
-By default, it's the HTTP headers of current task. It's an object with `string` values.
-
-*More details in [Got documentation](https://github.com/sindresorhus/got/blob/main/documentation/2-options.md#headers).*
-
-### `proxyUrl`
-
-It's a string representing the proxy server in the format of `protocol://username:password@hostname:port`.
-
-For example, an Apify proxy server looks like this: `http://auto:[email protected]:8000`.
-
-Basic Crawler does not have the concept of a session or proxy, therefore we need to manually pass the `proxyUrl` option:
-
-```ts
-import { BasicCrawler } from 'crawlee';
-
-const crawler = new BasicCrawler({
- async requestHandler({ sendRequest, log }) {
- const res = await sendRequest({
- proxyUrl: 'http://auto:[email protected]:8000',
- });
- log.info('received body', res.body);
- },
-});
-```
-
-We use proxies to hide our real IP address.
-
-*More details in [Got Scraping documentation](https://github.com/apify/got-scraping#proxyurl).*
-
-### `sessionToken`
-
-It's a non-primitive object used as a key when generating browser fingerprint. Fingerprints with the same token don't change.
-This can be used to retain the `user-agent` header when using the same Apify Session.
-
-*More details in [Got Scraping documentation](https://github.com/apify/got-scraping#sessiontoken).*
-
-### `responseType`
-
-This option defines how the response should be parsed.
-
-By default, we fetch HTML websites - that is plaintext. Hence, we set `responseType` to `'text'`. However, JSON is possible as well:
-
-```ts
-import { BasicCrawler } from 'crawlee';
-
-const crawler = new BasicCrawler({
- async requestHandler({ sendRequest, log }) {
- const res = await sendRequest({ responseType: 'json' });
- log.info('received body', res.body);
- },
-});
-```
-
-*More details in [Got documentation](https://github.com/sindresorhus/got/blob/main/documentation/2-options.md#responsetype).*
-
-### `cookieJar`
-
-`Got` uses a `cookieJar` to manage cookies. It's an object with an interface of a [`tough-cookie` package](https://github.com/salesforce/tough-cookie).
-
-Example:
-
-```ts
-import { BasicCrawler } from 'crawlee';
-import { CookieJar } from 'tough-cookie';
-
-const cookieJar = new CookieJar();
-
-const crawler = new BasicCrawler({
- async requestHandler({ sendRequest, log }) {
- const res = await sendRequest({ cookieJar });
- log.info('received body', res.body);
- },
-});
-```
-
-*More details in*
-- *[Got documentation](https://github.com/sindresorhus/got/blob/main/documentation/2-options.md#cookiejar)*
-- *[Tough Cookie documentation](https://github.com/salesforce/tough-cookie#cookiejarstore-options)*
-
-### `retry.limit`
-
-This option specifies the maximum number of `Got` retries.
-
-By default, `retry.limit` is set to `0`. This is because Crawlee has its own (complicated enough) retry management.
-
-We suggest NOT changing this value for stability reasons.
-
-### `useHeaderGenerator`
-
-It's a boolean for whether to generate browser headers. By default, it's set to `true`, and we recommend keeping this for better results.
-
-### `headerGeneratorOptions`
-
-This option represents an object how to generate browser fingerprint. Example:
-
-```ts
-import { BasicCrawler } from 'crawlee';
-
-const crawler = new BasicCrawler({
- async requestHandler({ sendRequest, log }) {
- const res = await sendRequest({
- headerGeneratorOptions: {
- devices: ['mobile', 'desktop'],
- locales: ['en-US'],
- operatingSystems: ['windows', 'macos', 'android', 'ios'],
- browsers: ['chrome', 'edge', 'firefox', 'safari'],
- },
- });
- log.info('received body', res.body);
- },
-});
-```
-
-*More details in [`HeaderGeneratorOptions` documentation](https://apify.github.io/fingerprint-suite/api/fingerprint-generator/interface/HeaderGeneratorOptions/).*
-
-**Related links**
-
-- [Got documentation](https://github.com/sindresorhus/got#documentation)
-- [Got Scraping documentation](https://github.com/apify/got-scraping)
-- [Header Generator documentation](https://apify.github.io/fingerprint-suite/docs/guides/fingerprint-generator/)
diff --git a/docs/guides/send-request.mdx b/docs/guides/send-request.mdx
new file mode 100644
index 000000000..67e9b8548
--- /dev/null
+++ b/docs/guides/send-request.mdx
@@ -0,0 +1,109 @@
+---
+id: send-request
+title: Sending HTTP requests
+description: Send HTTP requests from a request handler with the sendRequest helper
+---
+
+import ApiLink from '@site/src/components/ApiLink';
+
+## Intro
+
+Every crawler passes a <ApiLink to="basic-crawler/interface/BasicCrawlingContext#sendRequest">`sendRequest()`</ApiLink> helper to the request handler. `BasicCrawler` doesn't download anything on its own, so this is how it fetches the current request. Other crawlers can use it to send additional requests, for example to call an API.
+
+```ts
+import { BasicCrawler } from 'crawlee';
+
+const crawler = new BasicCrawler({
+ async requestHandler({ sendRequest, log }) {
+ const response = await sendRequest();
+ log.info('received body', { body: await response.text() });
+ },
+});
+```
+
+`sendRequest()` uses the crawler's HTTP client, which is `ImpitHttpClient` by default (see the [HTTP clients guide](./http-clients) for the alternatives), together with the cookies, proxy and browser fingerprint of the current session. It returns a standard [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response), so you read the body with `response.text()`, `response.json()` or `response.arrayBuffer()`. Like `fetch`, it follows redirects and doesn't throw on 4xx or 5xx status codes, so check `response.ok` or `response.status` yourself.
+
+## `sendRequest` API
+
+```ts
+sendRequest(
+ requestOverrides?: Partial<HttpRequestOptions>,
+ optionsOverrides?: SendRequestOptions,
+): Promise<Response>
+```
+
+### Request overrides
+
+The first argument (<ApiLink to="types/interface/HttpRequestOptions">`HttpRequestOptions`</ApiLink>) describes the request. Anything you leave out is taken from the request currently being processed.
+
+- `url` and `method` replace the URL and the HTTP method.
+- `headers` is a `Headers` instance merged into the headers of the current request.
+- `body`, `json` and `form` replace the payload. Use at most one of them. `json` and `form` also set the `content-type` header, unless you set it yourself.
+- `searchParams` replaces the query string of the URL.
+- `username` and `password` set the `authorization` header for HTTP Basic authentication.
+
+```ts
+import { BasicCrawler } from 'crawlee';
+
+const crawler = new BasicCrawler({
+ async requestHandler({ sendRequest, log }) {
+ const response = await sendRequest({
+ url: 'https://api.example.com/search',
+ method: 'POST',
+ headers: new Headers({ 'x-api-key': 'my-api-key' }),
+ json: { query: 'crawlee' },
+ });
+ log.info('received results', await response.json());
+ },
+});
+```
+
+### Request options
+
+The second argument (<ApiLink to="types/interface/SendRequestOptions">`SendRequestOptions`</ApiLink>) controls how the request is sent.
+
+- `proxyUrl` sends the request through the given proxy instead of the session's proxy.
+- `cookieJar` replaces the session's cookie jar.
+- `timeoutMillis` aborts the request after the given number of milliseconds, and `signal` aborts it when the `AbortSignal` fires.
+- `ignoreTlsErrors` skips TLS certificate checks, if the HTTP client supports it.
+
+The request overrides accept `proxyUrl`, `cookieJar`, `timeout` and `signal` too. When an option is set in both arguments, the one from the second argument is used.
+
+### Proxies
+
+By default, the request goes through the proxy of the current session, which comes from the crawler's `proxyConfiguration`. To use a different proxy, pass its URL in the format of `protocol://username:password@hostname:port`:
+
+```ts
+import { BasicCrawler } from 'crawlee';
+
+const crawler = new BasicCrawler({
+ async requestHandler({ sendRequest, log }) {
+ const response = await sendRequest({}, { proxyUrl: 'http://auto:[email protected]:8000' });
+ log.info('received body', { body: await response.text() });
+ },
+});
+```
+
+Note that a fixed `proxyUrl` bypasses the proxy rotation done by sessions.
+
+### Cookies
+
+By default, cookies are read from and saved to the cookie jar of the current session. You can pass any cookie jar compatible with the [`tough-cookie`](https://github.com/salesforce/tough-cookie) `CookieJar` instead:
+
+```ts
+import { BasicCrawler } from 'crawlee';
+import { CookieJar } from 'tough-cookie';
+
+const cookieJar = new CookieJar();
+
+const crawler = new BasicCrawler({
+ async requestHandler({ sendRequest, log }) {
+ const response = await sendRequest({}, { cookieJar });
+ log.info('received body', { body: await response.text() });
+ },
+});
+```
+
+### Browser fingerprints
+
+The HTTP client is responsible for making requests look like they come from a real browser, so there are no per-request options for that. To change this behavior, configure or replace the crawler's `httpClient`. See the [HTTP clients guide](./http-clients) and the [avoid getting blocked guide](./avoid-blocking).
diff --git a/docs/upgrading/upgrading-v3.md b/docs/upgrading/upgrading-v3.md
index 94a538630..2ff764d2d 100644
--- a/docs/upgrading/upgrading-v3.md
+++ b/docs/upgrading/upgrading-v3.md
@@ -256,7 +256,7 @@ const crawler = new BasicCrawler({
### How to use `sendRequest()`?
-See [the Got Scraping guide](../guides/got-scraping.mdx).
+See [the `sendRequest` guide](../guides/send-request.mdx).
### Removed options
diff --git a/packages/basic-crawler/src/internals/send-request.ts b/packages/basic-crawler/src/internals/send-request.ts
index 8706f8227..89e863d51 100644
--- a/packages/basic-crawler/src/internals/send-request.ts
+++ b/packages/basic-crawler/src/internals/send-request.ts
@@ -1,6 +1,9 @@
+import { Readable } from 'node:stream';
+
import type { Request as CrawleeRequest } from '@crawlee/core';
import type { BaseHttpClient } from '@crawlee/http-client';
import type { HttpRequestOptions, ISession, SendRequestOptions } from '@crawlee/types';
+import { processHttpRequestOptions } from '@crawlee/utils/internal';
/**
* Prepares a function to be used as the `sendRequest` context helper.
@@ -16,8 +19,6 @@ export function createSendRequest(httpClient: BaseHttpClient, originRequest: Cra
overrideOptions: SendRequestOptions = {},
): Promise<Response> => {
const baseRequest = originRequest.intoFetchAPIRequest();
- const mergedUrl = overrideRequest.url ?? baseRequest.url;
- const mergedMethod = overrideRequest.method ?? baseRequest.method;
const mergedHeaders = new Headers(baseRequest.headers);
if (overrideRequest.headers) {
@@ -26,17 +27,27 @@ export function createSendRequest(httpClient: BaseHttpClient, originRequest: Cra
});
}
- const request = new Request(mergedUrl, {
- method: mergedMethod,
+ const opts = processHttpRequestOptions({
+ ...overrideRequest,
+ url: overrideRequest.url ?? baseRequest.url,
+ method: overrideRequest.method ?? originRequest.method,
headers: mergedHeaders,
- body: overrideRequest.body ?? baseRequest.body,
+ });
+
+ const request = new Request(opts.url, {
+ method: opts.method,
+ headers: opts.headers,
+ body: opts.body ? Readable.toWeb(opts.body) : baseRequest.body,
+ // Node-specific option to make the request body work with streams
+ duplex: 'half',
} as RequestInit);
return httpClient.sendRequest(request, {
session,
- cookieJar: overrideOptions?.cookieJar ?? session.cookieJar,
- timeoutMillis: overrideOptions.timeoutMillis,
- signal: overrideOptions.signal,
+ cookieJar: overrideOptions.cookieJar ?? opts.cookieJar ?? session.cookieJar,
+ proxyUrl: overrideOptions.proxyUrl ?? opts.proxyUrl,
+ timeoutMillis: overrideOptions.timeoutMillis ?? opts.timeout,
+ signal: overrideOptions.signal ?? opts.signal,
ignoreTlsErrors: overrideOptions.ignoreTlsErrors,
});
};
diff --git a/packages/http-crawler/src/internals/http-crawler.ts b/packages/http-crawler/src/internals/http-crawler.ts
index 12189e33e..44229f1e7 100644
--- a/packages/http-crawler/src/internals/http-crawler.ts
+++ b/packages/http-crawler/src/internals/http-crawler.ts
@@ -32,7 +32,7 @@ import {
} from '@crawlee/basic';
import { ResponseWithUrl } from '@crawlee/http-client';
import type { Awaitable, Dictionary, ISession } from '@crawlee/types';
-import { parseArgument, RETRY_CSS_SELECTORS, schemas } from '@crawlee/utils/internal';
+import { parseArgument, processHttpRequestOptions, RETRY_CSS_SELECTORS, schemas } from '@crawlee/utils/internal';
import type { Cheerio, CheerioAPI } from 'cheerio';
import type { AnyNode } from 'domhandler';
import { isTypeValid, parse as parseContentType } from 'content-type';
@@ -42,7 +42,7 @@ import { z } from 'zod';
import { addTimeoutToPromise, storage, TimeoutError, tryCancel } from '@apify/timeout';
-import { extractCharsetFromHtmlBytes, parseContentTypeFromResponse, processHttpRequestOptions } from './utils.js';
+import { extractCharsetFromHtmlBytes, parseContentTypeFromResponse } from './utils.js';
/**
* Default mime types, which HttpScraper supports.
diff --git a/packages/http-crawler/src/internals/utils.ts b/packages/http-crawler/src/internals/utils.ts
index 5170ace5a..1d70e7ef3 100644
--- a/packages/http-crawler/src/internals/utils.ts
+++ b/packages/http-crawler/src/internals/utils.ts
@@ -1,66 +1,12 @@
import { extname } from 'node:path';
-import { Readable } from 'node:stream';
-import type { HttpRequest, HttpRequestOptions } from '@crawlee/types';
-import { applySearchParams, parseArgument } from '@crawlee/utils/internal';
+import { parseArgument } from '@crawlee/utils/internal';
import { isTypeValid, parse as parseContentType } from 'content-type';
import mime from 'mime-types';
import { z } from 'zod';
const responseWithUrlSchema = z.looseObject({ url: z.url(), headers: z.looseObject({}) });
-/**
- * Converts {@apilink HttpRequestOptions} to a {@apilink HttpRequest}.
- */
-export function processHttpRequestOptions({
- searchParams,
- form,
- json,
- username,
- password,
- ...request
-}: HttpRequestOptions): HttpRequest {
- const url = new URL(request.url);
- const headers = new Headers(request.headers);
-
- applySearchParams(url, searchParams);
-
- if ([request.body, form, json].filter((value) => value !== undefined).length > 1) {
- throw new Error('At most one of `body`, `form` and `json` may be specified in sendRequest arguments');
- }
-
- const body = (() => {
- if (form !== undefined) {
- return Readable.from(new URLSearchParams(form).toString());
- }
-
- if (json !== undefined) {
- return Readable.from(JSON.stringify(json));
- }
-
- if (request.body !== undefined) {
- return Readable.from(request.body);
- }
-
- return undefined;
- })();
-
- if (form !== undefined && !headers.has('content-type')) {
- headers.set('content-type', 'application/x-www-form-urlencoded');
- }
-
- if (json !== undefined && !headers.has('content-type')) {
- headers.set('content-type', 'application/json');
- }
-
- if (username !== undefined || password !== undefined) {
- const encodedAuth = Buffer.from(`${username ?? ''}:${password ?? ''}`).toString('base64');
- headers.set('authorization', `Basic ${encodedAuth}`);
- }
-
- return { ...request, body, url, headers };
-}
-
/**
* Scans the first 1024 bytes of an HTML document (as latin1) to extract the charset
* declared via `<meta charset>` or `<meta http-equiv="Content-Type" content="...;charset=...">`.
diff --git a/packages/utils/src/internal.ts b/packages/utils/src/internal.ts
index 736a7100f..021d92579 100644
--- a/packages/utils/src/internal.ts
+++ b/packages/utils/src/internal.ts
@@ -3,6 +3,7 @@ export type { CheerioAPI, Cheerio, Element } from './internals/cheerio.js';
export { extractUrlsFromCheerio } from './internals/cheerio.js';
export { tryAbsoluteURL } from './internals/extract-urls.js';
export { expandShadowRoots, URL_NO_COMMAS_REGEX, URL_WITH_COMMAS_REGEX } from './internals/general.js';
+export { processHttpRequestOptions } from './internals/http-request.js';
export * from './internals/iterables.js';
export { MutationJournal } from './internals/mutation-journal.js';
export * from './internals/url.js';
diff --git a/packages/utils/src/internals/http-request.ts b/packages/utils/src/internals/http-request.ts
new file mode 100644
index 000000000..3c3e2e27d
--- /dev/null
+++ b/packages/utils/src/internals/http-request.ts
@@ -0,0 +1,57 @@
+import { Readable } from 'node:stream';
+
+import type { HttpRequest, HttpRequestOptions } from '@crawlee/types';
+
+import { applySearchParams } from './url.js';
+
+/**
+ * Converts {@apilink HttpRequestOptions} to a {@apilink HttpRequest}.
+ */
+export function processHttpRequestOptions({
+ searchParams,
+ form,
+ json,
+ username,
+ password,
+ ...request
+}: HttpRequestOptions): HttpRequest {
+ const url = new URL(request.url);
+ const headers = new Headers(request.headers);
+
+ applySearchParams(url, searchParams);
+
+ if ([request.body, form, json].filter((value) => value !== undefined).length > 1) {
+ throw new Error('At most one of `body`, `form` and `json` may be specified in sendRequest arguments');
+ }
+
+ const body = (() => {
+ if (form !== undefined) {
+ return Readable.from(new URLSearchParams(form).toString());
+ }
+
+ if (json !== undefined) {
+ return Readable.from(JSON.stringify(json));
+ }
+
+ if (request.body !== undefined) {
+ return Readable.from(request.body);
+ }
+
+ return undefined;
+ })();
+
+ if (form !== undefined && !headers.has('content-type')) {
+ headers.set('content-type', 'application/x-www-form-urlencoded');
+ }
+
+ if (json !== undefined && !headers.has('content-type')) {
+ headers.set('content-type', 'application/json');
+ }
+
+ if (username !== undefined || password !== undefined) {
+ const encodedAuth = Buffer.from(`${username ?? ''}:${password ?? ''}`).toString('base64');
+ headers.set('authorization', `Basic ${encodedAuth}`);
+ }
+
+ return { ...request, body, url, headers };
+}
diff --git a/test/core/crawlers/basic-crawler.test.ts b/test/core/crawlers/basic-crawler.test.ts
index b7bc898df..650ab5c1a 100644
--- a/test/core/crawlers/basic-crawler.test.ts
+++ b/test/core/crawlers/basic-crawler.test.ts
@@ -3,6 +3,7 @@ import { resolve } from 'node:path';
import type { Server } from 'node:http';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
+import { text } from 'node:stream/consumers';
import type {
BasicCrawlerOptions,
@@ -52,6 +53,7 @@ import { FileSystemStorageBackend } from '@crawlee/fs-storage';
import type { Dictionary, ISession, ProxyInfo } from '@crawlee/types';
import { RobotsTxtFile, sleep } from '@crawlee/utils';
import express from 'express';
+import { CookieJar } from 'tough-cookie';
import type { Mock } from 'vitest';
import { afterAll, beforeAll, beforeEach, describe, expect, test, vitest } from 'vitest';
import { z } from 'zod';
@@ -3077,6 +3079,129 @@ describe('BasicCrawler', () => {
expect(captured).toEqual([true]);
});
+ test('forwards proxyUrl to the http client', async () => {
+ const captured: (string | undefined)[] = [];
+
+ const crawler = new BasicCrawler({
+ httpClient: Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
+ async sendRequest(_request: globalThis.Request, options?: { proxyUrl?: string }) {
+ captured.push(options?.proxyUrl);
+ return new Response('ok');
+ },
+ }),
+ async requestHandler({ sendRequest }) {
+ await sendRequest({}, { proxyUrl: 'http://options-proxy.com' });
+ await sendRequest({ proxyUrl: 'http://request-proxy.com' });
+ await sendRequest();
+ await sendRequest(
+ { proxyUrl: 'http://request-proxy.com' },
+ { proxyUrl: 'http://options-proxy.com' },
+ );
+ },
+ });
+
+ await crawler.run([url]);
+
+ expect(captured).toEqual([
+ 'http://options-proxy.com',
+ 'http://request-proxy.com',
+ undefined,
+ 'http://options-proxy.com',
+ ]);
+ });
+
+ test('applies searchParams, json, form and basic auth to the request', async () => {
+ const captured: { url: string; method: string; headers: Record<string, string>; body: string }[] = [];
+
+ const crawler = new BasicCrawler({
+ maxRequestRetries: 0,
+ httpClient: Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
+ async sendRequest(request: globalThis.Request) {
+ captured.push({
+ url: request.url,
+ method: request.method,
+ headers: Object.fromEntries(request.headers),
+ body: request.body ? await text(request.body) : '',
+ });
+ return new Response('ok');
+ },
+ }),
+ async requestHandler({ sendRequest }) {
+ await sendRequest({ searchParams: { foo: 'bar' } });
+ await sendRequest({ method: 'POST', json: { foo: 'bar' } });
+ await sendRequest({ method: 'POST', form: { foo: 'bar' } });
+ await sendRequest({ username: 'user', password: 'pass' });
+ },
+ });
+
+ await crawler.run([url]);
+
+ expect(captured).toMatchObject([
+ { url: `${url}?foo=bar`, method: 'GET', body: '' },
+ { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"foo":"bar"}' },
+ {
+ method: 'POST',
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
+ body: 'foo=bar',
+ },
+ { headers: { authorization: `Basic ${Buffer.from('user:pass').toString('base64')}` } },
+ ]);
+ });
+
+ test('sends the payload of the crawled request', async () => {
+ const captured: { method: string; body: string }[] = [];
+
+ const crawler = new BasicCrawler({
+ maxRequestRetries: 0,
+ httpClient: Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
+ async sendRequest(request: globalThis.Request) {
+ captured.push({ method: request.method, body: await request.text() });
+ return new Response('ok');
+ },
+ }),
+ async requestHandler({ sendRequest }) {
+ await sendRequest();
+ },
+ });
+
+ await crawler.run([{ url, method: 'POST', payload: 'foo=bar' }]);
+
+ expect(captured).toEqual([{ method: 'POST', body: 'foo=bar' }]);
+ });
+
+ test('forwards timeout, signal and cookieJar from the request options to the http client', async () => {
+ const captured: { timeoutMillis?: number; signal?: AbortSignal; cookieJar?: unknown }[] = [];
+ const { signal } = new AbortController();
+ const cookieJar = new CookieJar();
+
+ const crawler = new BasicCrawler({
+ maxRequestRetries: 0,
+ httpClient: Object.assign(Object.create(BaseHttpClient.prototype) as BaseHttpClient, {
+ async sendRequest(
+ _request: globalThis.Request,
+ options?: { timeoutMillis?: number; signal?: AbortSignal; cookieJar?: unknown },
+ ) {
+ captured.push({
+ timeoutMillis: options?.timeoutMillis,
+ signal: options?.signal,
+ cookieJar: options?.cookieJar,
+ });
+ return new Response('ok');
+ },
+ }),
+ async requestHandler({ sendRequest }) {
+ await sendRequest({ timeout: 1000, signal, cookieJar });
+ },
+ });
+
+ await crawler.run([url]);
+
+ expect(captured).toHaveLength(1);
+ expect(captured[0].timeoutMillis).toBe(1000);
+ expect(captured[0].signal).toBe(signal);
+ expect(captured[0].cookieJar).toBe(cookieJar);
+ });
+
test('proxyUrl TypeScript support', async () => {
const crawler = new BasicCrawler({
async requestHandler({ sendRequest }) {
diff --git a/test/core/process-http-request-options.test.ts b/test/core/process-http-request-options.test.ts
index cbff3c366..78f7ee1d7 100644
--- a/test/core/process-http-request-options.test.ts
+++ b/test/core/process-http-request-options.test.ts
@@ -1,7 +1,7 @@
import { Readable } from 'node:stream';
import { text } from 'node:stream/consumers';
-import { processHttpRequestOptions } from '../../packages/http-crawler/src/internals/utils.js';
+import { processHttpRequestOptions } from '@crawlee/utils/internal';
describe('processHttpRequestOptions', () => {
test('applies search parameters to the request URL', () => {
diff --git a/website/sidebars.js b/website/sidebars.js
index a976a3a89..19d034b84 100644
--- a/website/sidebars.js
+++ b/website/sidebars.js
@@ -48,7 +48,7 @@ module.exports = {
'guides/avoid-blocking',
'guides/cookie-modals',
'guides/impit-http-client/impit-http-client',
- 'guides/got-scraping',
+ 'guides/send-request',
'guides/typescript-project',
'guides/public-api',
'guides/docker-images',