* Sends the request. * @param body The body of the request.
(body = null)
| 132 | * @param body The body of the request. |
| 133 | */ |
| 134 | async send(body = null) { |
| 135 | if (this.readyState !== 1) { |
| 136 | throw new Error('send() can only be called when state is OPENED.'); |
| 137 | } |
| 138 | |
| 139 | this._abortController = new AbortController(); |
| 140 | const signal = this._abortController.signal; |
| 141 | |
| 142 | // Handle timeout |
| 143 | let timeoutID; |
| 144 | if (this.timeout > 0) { |
| 145 | timeoutID = setTimeout( |
| 146 | () => this._abortController.abort(new DOMException('The user aborted a request.', 'TimeoutError')), |
| 147 | this.timeout |
| 148 | ); |
| 149 | } |
| 150 | |
| 151 | const fetchOptions = { |
| 152 | method: this._method, |
| 153 | headers: this._headers, |
| 154 | body: body, |
| 155 | signal: signal, |
| 156 | credentials: this.withCredentials ? 'include' : 'same-origin', |
| 157 | }; |
| 158 | |
| 159 | try { |
| 160 | const response = await fetch(this._url, fetchOptions); |
| 161 | |
| 162 | // Populate response properties once headers are received |
| 163 | this.status = response.status; |
| 164 | this.statusText = response.statusText; |
| 165 | this.responseURL = response.url; |
| 166 | this._responseHeaders = response.headers; |
| 167 | this._changeReadyState(2); // 2: HEADERS_RECEIVED |
| 168 | |
| 169 | // Start processing the body |
| 170 | this._changeReadyState(3); // 3: LOADING |
| 171 | |
| 172 | if (!response.body) { |
| 173 | throw new Error("Response has no body to read."); |
| 174 | } |
| 175 | |
| 176 | const reader = response.body.getReader(); |
| 177 | const contentLength = +response.headers.get('Content-Length'); |
| 178 | |
| 179 | let receivedLength = 0; |
| 180 | // When streaming data don't collect all of the chunks into one large chunk. It's up to the |
| 181 | // user to collect the data as it comes in. |
| 182 | const chunks = this._streamData ? null : []; |
| 183 | |
| 184 | while (true) { |
| 185 | const { done, value } = await reader.read(); |
| 186 | if (done) { |
| 187 | break; |
| 188 | } |
| 189 | |
| 190 | if (!this._streamData) { |
| 191 | chunks.push(value); |
no test coverage detected