* Initializes a request. * @param {string} method The HTTP request method (e.g., 'GET', 'POST'). * @param {string} url The URL to send the request to. * @param {boolean} [async=true] This parameter is ignored as Fetch is always async. * @param {string|null} [user=null] The username for b
(method, url, async = true, user = null, password = null)
| 61 | * @param {string|null} [password=null] The password for basic authentication. |
| 62 | */ |
| 63 | open(method, url, async = true, user = null, password = null) { |
| 64 | if (this.readyState !== 0 && this.readyState !== 4) { |
| 65 | console.warn("FetchXHR.open() called while a request is in progress."); |
| 66 | this.abort(); |
| 67 | } |
| 68 | |
| 69 | // Reset internal state for the new request |
| 70 | this._method = method; |
| 71 | this._url = url; |
| 72 | this._headers = {}; |
| 73 | this._responseHeaders = null; |
| 74 | |
| 75 | // The async parameter is part of the XHR API but is an error here because |
| 76 | // the Fetch API is inherently asynchronous and does not support synchronous requests. |
| 77 | if (!async) { |
| 78 | throw new Error("FetchXHR does not support synchronous requests."); |
| 79 | } |
| 80 | |
| 81 | // Handle Basic Authentication if user/password are provided. |
| 82 | // This creates a base64-encoded string and sets the Authorization header. |
| 83 | if (user) { |
| 84 | const credentials = btoa(`${user}:${password ?? ''}`); |
| 85 | this._headers['Authorization'] = `Basic ${credentials}`; |
| 86 | } |
| 87 | |
| 88 | this._changeReadyState(1); // 1: OPENED |
| 89 | } |
| 90 | |
| 91 | /** |
| 92 | * Sets the value of an HTTP request header. |