How to Use http.request in Node.js: Simple Guide
In Node.js, use
http.request to make HTTP requests by creating a request object with options and handling the response with event listeners. You write the request data if needed, then call req.end() to send it. This method gives you full control over the request process.Syntax
The http.request method creates an HTTP request. It takes an options object describing the request and a callback function to handle the response.
options: Includeshostname,port,path,method, and headers.callback: Called with the response object to read data.req.write(data): Sends request body data if needed.req.end(): Signals that request is complete and sends it.
javascript
const http = require('http'); const options = { hostname: 'example.com', port: 80, path: '/path', method: 'GET', headers: { 'Content-Type': 'application/json' } }; const req = http.request(options, (res) => { res.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); res.on('end', () => { console.log('No more data in response.'); }); }); req.on('error', (e) => { console.error(`Problem with request: ${e.message}`); }); req.end();
Example
This example makes a simple GET request to jsonplaceholder.typicode.com to fetch a post and prints the response body.
javascript
const http = require('http'); const options = { hostname: 'jsonplaceholder.typicode.com', port: 80, path: '/posts/1', method: 'GET' }; const req = http.request(options, (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log('Response received:'); console.log(data); }); }); req.on('error', (e) => { console.error(`Request error: ${e.message}`); }); req.end();
Output
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Common Pitfalls
- Forgetting to call
req.end()will cause the request to never send. - Not handling the
errorevent on the request can crash your app on network errors. - Trying to read response data without listening to
dataandendevents will give incomplete results. - Using the wrong HTTP method or missing headers can cause server errors.
javascript
const http = require('http'); // Wrong: Missing req.end(), request never sent const req1 = http.request({ hostname: 'example.com', method: 'GET' }, (res) => { res.on('data', (chunk) => console.log(chunk.toString())); }); // req1.end(); // This line is missing // Right: Always call req.end() const req2 = http.request({ hostname: 'example.com', method: 'GET' }, (res) => { res.on('data', (chunk) => console.log(chunk.toString())); }); req2.end();
Quick Reference
Remember these key points when using http.request:
- Set
optionscorrectly with hostname, path, method, and headers. - Listen to
responseeventsdataandendto read the response body. - Always call
req.end()to send the request. - Handle
errorevents on both request and response.
Key Takeaways
Always call req.end() to send the HTTP request.
Use event listeners on the response to read data chunks and detect end of response.
Handle errors on the request to avoid crashes.
Set request options like hostname, path, and method correctly.
http.request gives full control but requires manual handling of data and events.