Node.js http Module
Node.js's http The module is one of Node.js's built-in core modules; it allows developers to create HTTP servers and clients. Through this module, we can easily handle HTTP requests and responses, and build web applications or API services.
http The module provides the ability to create servers and initiate HTTP requests, and is the foundation for building web applications. It supports the HTTP/1.1 protocol and provides a rich set of APIs to handle various HTTP-related operations.
Create an HTTP server
Use http Creating a server with the module is very simple; here is the most basic example:
Example
const
http
=
require
(
'http'
)
;
// Create an HTTP server
const
server
=
http.
createServer
(
(
req
,
res
)
=>
{
// Set response headers
res.
writeHead
(
200
,
{
'Content-Type'
:
'text/plain'
}
)
;
// Send response data
res.
end
(
'Hello, World!\n'
)
;
}
)
;
// Listen on port 3000
server.
listen
(
3000
,
(
)
=>
{
console.
log
(
'Server running at http://localhost:3000/'
)
;
}
)
;
Code Analysis
require('http')- Import Node.js's http modulehttp.createServer()- Create an HTTP server instance- Callback Function
(req, res) => {...}- Handle every HTTP request
req - Request object, containing information about the request sent by the clientres - Response object, used to send responses to the clientres.writeHead()- Set response headersres.end()- End the response and send dataserver.listen()- Start the server listening on a specified port
Handling HTTP Requests
An HTTP server needs to be able to handle different types of requests. Let's look at how to parse request information:
Example
const
http
=
require
(
'http'
)
;
const
server
=
http.
createServer
(
(
req
,
res
)
=>
{
// Get the request method, URL, and headers
const
{
method
,
url
,
headers
}
=
req
;
// Log the request information
console.
log
(
`Received $
{
method
}
request, path
:
$
{
url
}
`
)
;
console.
log
(
'Request headers:'
,
headers
)
;
// Handle according to the request method
if
(
method
===
'GET'
)
{
res.
writeHead
(
200
,
{
'Content-Type'
:
'text/plain'
}
)
;
res.
end
(
'This is a GET request\n'
)
;
}
else
if
(
method
===
'POST'
)
{
let body
=
''
;
// Collect POST data
req.
on
(
'data'
,
chunk
=>
{
body
+=
chunk
;
}
)
;
// Data reception complete
req.
on
(
'end'
,
(
)
=>
{
console.
log
(
'POST data:'
,
body
)
;
res.
writeHead
(
200
,
{
'Content-Type'
:
'text/plain'
}
)
;
res.
end
(
'Data received\n'
)
;
}
)
;
}
else
{
res.
writeHead
(
405
,
{
'Content-Type'
:
'text/plain'
}
)
;
res.
end
(
'Method not allowed\n'
)
;
}
}
)
;
server.
listen
(
3000
)
;
Common Properties of the Request Object (req)
req.method: HTTP request method (GET, POST, PUT, DELETE, etc.)req.url: The URL path of the requestreq.headers: Request headers objectreq.httpVersion: HTTP protocol version
Common Methods of the Response Object (res)
res.writeHead(statusCode, headers): Set the response status code and headersres.write(data): Write the response bodyres.end([data]): End the response, optionally sending final datares.setHeader(name, value): Set response headers
Make an HTTP request
http The module can not only create servers but also act as a client to initiate HTTP requests:
Example
const
http
=
require
(
'http'
)
;
// Initiate a GET request
http.
get
(
'http://jsonplaceholder.typicode.com/posts/1'
,
(
res
)
=>
{
let data
=
''
;
// Receive data
res.
on
(
'data'
,
(
chunk
)
=>
{
data
+=
chunk
;
}
)
;
// Data reception complete
res.
on
(
'end'
,
(
)
=>
{
console.
log
(
'Response data:'
,
JSON.
parse
(
data
)
)
;
}
)
;
}
)
.
on
(
'error'
,
(
err
)
=>
{
console.
error
(
'Request error:'
,
err
)
;
}
)
;
Initiating a POST Request
Example
const
http
=
require
(
'http'
)
;
// Request options
const
options
=
{
hostname
:
'jsonplaceholder.typicode.com'
,
port
:
80
,
path
:
'/posts'
,
method
:
'POST'
,
headers
:
{
'Content-Type'
:
'application/json'
,
}
}
;
// Create the request
const
req
=
http.
request
(
options
,
(
res
)
=>
{
let data
=
''
;
res.
on
(
'data'
,
(
chunk
)
=>
{
data
+=
chunk
;
}
)
;
res.
on
(
'end'
,
(
)
=>
{
console.
log
(
'Response:'
,
JSON.
parse
(
data
)
)
;
}
)
;
}
)
;
// Handle errors
req.
on
(
'error'
,
(
err
)
=>
{
console.
error
(
'Request error:'
,
err
)
;
}
)
;
// Write request data
const
postData
=
JSON.
stringify
(
{
title
:
'foo'
,
body
:
'bar'
,
userId
:
1
}
)
;
req.
write
(
postData
)
;
req.
end
(
)
;
Practical Application Scenarios
1. Create a RESTful API
Example
const
http
=
require
(
'http'
)
;
const
server
=
http.
createServer
(
(
req
,
res
)
=>
{
const
{
method
,
url
}
=
req
;
// Simple routing handling
if
(
method
===
'GET'
&&
url
===
'/api/users'
)
{
res.
writeHead
(
200
,
{
'Content-Type'
:
'application/json'
}
)
;
res.
end
(
JSON.
stringify
(
[
{
id
:
1
,
name
:
'Alice'
}
,
{
id
:
2
,
name
:
'Bob'
}
]
)
)
;
}
else
if
(
method
===
'POST'
&&
url
===
'/api/users'
)
{
let body
=
''
;
req.
on
(
'data'
,
chunk
=>
body
+=
chunk
)
;
req.
on
(
'end'
,
(
)
=>
{
const
newUser
=
JSON.
parse
(
body
)
;
// Here you can save to a database
res.
writeHead
(
201
,
{
'Content-Type'
:
'application/json'
}
)
;
res.
end
(
JSON.
stringify
(
{
id
:
Date
.
now
(
)
,
...
newUser
}
)
)
;
}
)
;
}
else
{
res.
writeHead
(
404
,
{
'Content-Type'
:
'text/plain'
}
)
;
res.
end
(
'Not Found\n'
)
;
}
}
)
;
server.
listen
(
3000
)
;
2. Proxy Server
Example
const
http
=
require
(
'http'
)
;
const
proxy
=
http.
createServer
(
(
clientReq
,
clientRes
)
=>
{
// Initiate a request to the target server
const
options
=
{
hostname
:
'example.com'
,
port
:
80
,
path
:
clientReq.
url
,
method
:
clientReq.
method
,
headers
:
clientReq.
headers
}
;
const
proxyReq
=
http.
request
(
options
,
(
proxyRes
)
=>
{
// Forward the target server's response to the client
clientRes.
writeHead
(
proxyRes.
statusCode
,
proxyRes.
headers
)
;
proxyRes.
pipe
(
clientRes
)
;
}
)
;
// Forward the client's request body
clientReq.
pipe
(
proxyReq
)
;
}
)
;
proxy.
listen
(
8080
)
;
Best Practices
- Error handling: Always handle error events in requests and responses
- Performance considerations: For high-concurrency applications, consider using a connection pool
- Safety:
- Use streams: For large file transfers, use stream processing
- Consider frameworks: For complex applications, consider using frameworks such as Express and Koa
Summary
Node.js's http The module provides the fundamental capabilities for building network applications. Although many more advanced frameworks are available today, understanding http how the module works is essential for any Node.js developer. By mastering this core module, you can gain a better understanding of how web applications work and build custom solutions to meet your needs.
Node.js Built-in Modules