HTTP
http.request()
Creates an outgoing HTTP request. Call end even for a request without a body, handle request errors, and consume or discard the incoming response. A timeout event alone does not abort the request. Tested on Node.js 22.16.0. Example output (one line per entry): ["POST"].
Formal Syntax & Structure
nodejs syntaxnodejs
http.request(url[, options][, callback]); http.request(options[, callback])Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| url | string | URL | Destination in the URL overload. |
| options | object | Request options or options-only overload. |
| callback | Function | Response listener. |
Return Value
http.ClientRequest
Outgoing writable request.
Working Example
Example Snippetnodejs
import http from 'node:http';const server = http.createServer((req, res) => res.end(req.method));await new Promise(r => server.listen(0, '127.0.0.1', r));const url = 'http://127.0.0.1:' + server.address().port;try { const body = await new Promise((resolve, reject) => { const q = http.request(url, { method: 'POST' }, r => { let s = ''; r.setEncoding('utf8'); r.on('data', c => s += c); r.on('end', () => resolve(s)); r.on('error', reject); }); q.on('error', reject); q.end(); }); console.log(body);}finally { server.closeAllConnections(); await new Promise(r => server.close(r));}