Node.js GET/POST Requests
In many scenarios, our server needs to interact with the user's browser, such as form submissions.
Form submissions to the server generally use GET/POST requests.
In this chapter, we will introduce Node.js GET/POST requests.
Getting GET Request Content
Since a GET request is embedded directly in the path, the URL is the complete request path, including the part after ?, so you can manually parse the content after it as the parameters of the GET request.
In Node.js, you can use the URL constructor to parse the request URL.
The URL object is a standard tool in Node.js for parsing and manipulating URLs. It provides a convenient interface to access and modify the various components of a URL, such as the protocol, hostname, path, query parameters, and so on.
Example
const
http
=
require
(
'
http
'
)
;
const
util
=
require
(
'
util
'
)
;
http
.
createServer
(
(
req
,
res
)
=>
{
res
.
writeHead
(
200
,
{
'
Content-Type
'
:
'
text/plain; charset=utf-8
'
}
)
;
//
Use the URL constructor to parse the request URL
const
myUrl
=
new
URL
(
req
.
url
, `
http
:
//
${req.headers.host}`);
//
Output the various parts of the URL
res
.
end
(
util
.
inspect
(
{
href
:
myUrl
.
href
,
origin
:
myUrl
.
origin
,
protocol
:
myUrl
.
protocol
,
host
:
myUrl
.
host
,
hostname
:
myUrl
.
hostname
,
port
:
myUrl
.
port
,
pathname
:
myUrl
.
pathname
,
search
:
myUrl
.
search
,
searchParams
:
Object
.
fromEntries
(
myUrl
.
searchParams
)
//
Convert searchParams to a plain object
}
)
)
; }
)
.
listen
(
3000
)
;
console
.
log
(
"
Server is running at http://localhost:3000
"
)
;
Access in the browser http://localhost:3000/user?name=Runoob Tutorial&url=www.runoob.com Then view the returned result:

Getting URL Parameters
We can use the url.parse method to parse the parameters in a URL, as shown in the following code:
Example
const
http
=
require
(
'
http
'
)
;
http
.
createServer
(
(
req
,
res
)
=>
{
res
.
writeHead
(
200
,
{
'
Content-Type
'
:
'
text/plain; charset=utf-8
'
}
)
;
//
Use the URL constructor to parse the request URL
const
myUrl
=
new
URL
(
req
.
url
, `
http
:
//
${req.headers.host}`);
//
Get query parameters
const
name
=
myUrl
.
searchParams
.
get
(
"
name
"
)
;
const
siteUrl
=
myUrl
.
searchParams
.
get
(
"
url
"
)
;
res
.
write
(
"
Website name:
"
(
name
||
"
Not provided
"
)
)
;
res
.
write
(
"
\n
"
)
;
res
.
write
(
"
Website URL:
"
(
siteUrl
||
"
Not provided
"
)
)
;
res
.
end
(
)
; }
)
.
listen
(
3000
)
;
console
.
log
(
"
Server is running at http://localhost:3000
"
)
;
Access in the browser http://localhost:3000/user?name=Runoob Tutorial&url=www.runoob.com Then view the returned result:

URL Object
The following are the properties and methods of the URL object:
| Attribute / method | Description | Example output |
|---|---|---|
| href | The complete URL string | "http://example.com:8080/path?foo=bar#section" |
| origin | The origin of the URL, including the protocol, hostname, and port number (if present) | "http://example.com:8080" |
| protocol | The protocol part of the URL, followed by : |
"http:" |
| host | Hostname and port number | "example.com:8080" |
| hostname | Hostname, not including the port number | "example.com" |
| port | Port number (if specified) | "8080" |
| pathname | The pathname part | "/path" |
| search | The query string part, including the leading ? |
"?foo=bar&hello=world" |
| searchParams | URLSearchParams Object for manipulating query parameters |
{ foo: 'bar', hello: 'world' } |
| hash | The anchor part, containing # |
"#section" |
| Method | Description | Example Code | Example output |
|---|---|---|---|
| get(name) | Get the value of the query parameter with the specified name | myUrl.searchParams.get("foo") |
"bar" |
| append(name, value) | Append a new parameter to the query string | myUrl.searchParams.append("newKey", "newValue") |
?foo=bar&newKey=newValue |
| set(name, value) | Set the parameter with the specified name in the query string (update it if it already exists) | myUrl.searchParams.set("foo", "newBar") |
?foo=newBar |
| delete(name) | Delete the query parameter with the specified name | myUrl.searchParams.delete("foo") |
?hello=world |
| has(name) | Determine whether a parameter with the specified name exists in the query string | myUrl.searchParams.has("foo") |
true or false |
| forEach(callback) | Iterate over the key-value pairs of the query parameters and execute a callback function | myUrl.searchParams.forEach((v, k) => console.log(k, v)) |
Key-value pair output |
| toString() | Convert the query parameters to a string form, suitable for rebuilding a URL | myUrl.searchParams.toString() |
"foo=bar&hello=world" |
Example
const
myUrl
=
new
URL
(
"http://example.com/path?foo=bar&hello=world"
)
;
console.
log
(
myUrl.
pathname
)
;
// Output: /path
console.
log
(
myUrl.
searchParams
.
get
(
"foo"
)
)
;
// Output: bar
myUrl.
searchParams
.
append
(
"newKey"
,
"newValue"
)
;
console.
log
(
myUrl.
href
)
;
// Output: http://example.com/path?foo=bar&hello=world&newKey=newValue
Getting POST Request Content
In Node.js, handling a POST request typically requires using the http module to receive the data in the request body. POST request data is not contained in the URL like a GET request; instead, it is sent as the request body. Therefore, when receiving POST data in Node.js, you need to listen for and handle the data and end events of the request object.
- Listen for
dataEvents: When a chunk of data arrives at the server,datathe event is triggered, and the data chunk is passed as an argument to the callback. - Listen for
endEvents: When the entire request body has been received,endthe event is triggered, and at this point the complete POST data can be processed.
The following code shows how to use the http module in Node.js to handle POST requests:
Example
const
http
=
require
(
'http'
)
;
// Create an HTTP server
http.
createServer
(
(
req
,
res
)
=>
{
// Check whether the request method is POST
if
(
req.
method
===
'POST'
)
{
let body
=
''
;
// Listen for the data event to receive data chunk by chunk
req.
on
(
'data'
,
(
chunk
)
=>
{
body
+=
chunk
;
// Accumulate the received data chunks
}
)
;
// Listen for the end event, data reception complete
req.
on
(
'end'
,
(
)
=>
{
// Output the received POST data
console.
log
(
'Received POST data:'
,
body
)
;
// Set the response headers and content
res.
writeHead
(
200
,
{
'Content-Type'
:
'text/plain'
}
)
;
res.
end
(
'POST data received successfully!'
)
;
}
)
;
}
else
{
// Handling of non-POST requests
res.
writeHead
(
405
,
{
'Content-Type'
:
'text/plain'
}
)
;
res.
end
(
'Only POST requests are supported.'
)
;
}
}
)
.
listen
(
3000
,
(
)
=>
{
console.
log
(
'Server is running at http://localhost:3000'
)
;
}
)
;
Code explanation:
- Detect the request method: Through
req.method === 'POST'to determine whether the request type is POST. - Receive data: In
req.on('data')Accumulate data chunks in the event to form the complete data body. - Complete reception: In
req.on('end')Process the complete POST data in the event. - Respond to the client: After data reception and processing are complete, send a response to the client.
You can use the curl command to test a POST request:
curl -X POST -d "name=example&age=25" http://localhost:3000
Handle JSON data
If the POST request sends JSON data, you can parse the received data into an object in req.on('end'):
req.on('end', () => {
const parsedData = JSON.parse(body); // 将 JSON 字符串解析为对象
console.log('Received JSON data:', parsedData);
res.end('JSON data received successfully!');
});
querystring Module
The querystring module is used to handle URL query strings and POST request data.
For POST request data encoded as application/x-www-form-urlencoded, the querystring module can help parse the request body and convert it into a JavaScript object for easy access and manipulation.
Suppose the POST request data sent by the client is in the format application/x-www-form-urlencoded(for example, a form submission), with data in a form similar to name=example&age=25. After receiving the data, you can use the querystring.parse method to parse the data into an object.
Basic Syntax Structure Explanation
var
http
=
require
(
'
http
'
)
;
var
querystring
=
require
(
'
querystring
'
)
;
var
util
=
require
(
'
util
'
)
;
http
.
createServer
(
function
(
req
,
res
)
{
//
A post variable is defined to temporarily store the information of the request body
var
post
=
'
'
;
//
Through the data event listener of req, whenever request body data is received, it is accumulated into the post variable
req
.
on
(
'
data
'
,
function
(
chunk
)
{
post
+=
chunk
;
}
)
;
//
After the end event is triggered, post is parsed into the actual POST request format via querystring.parse, and then returned to the client.
req
.
on
(
'
end
'
,
function
(
)
{
post
=
querystring
.
parse
(
post
)
;
res
.
end
(
util
.
inspect
(
post
)
)
;
}
)
;
}
)
.
listen
(
3000
)
;
The following example form submits via POST and outputs the data:
Example
var
http
=
require
(
'
http
'
)
;
var
querystring
=
require
(
'
querystring
'
)
;
var
postHTML
=
'
'
'
'
'
'
'
'
;
http
.
createServer
(
function
(
req
,
res
)
{
var
body
=
"
"
;
req
.
on
(
'
data
'
,
function
(
chunk
)
{
body
+=
chunk
;
}
)
;
req
.
on
(
'
end
'
,
function
(
)
{
//
Parse parameters
body
=
querystring
.
parse
(
body
)
;
//
Set response header information and encoding
res
.
writeHead
(
200
,
{
'
Content-Type
'
:
'
text/html; charset=utf8
'
}
)
;
if
(
body
.
name
&&
body
.
url
)
{
//
Output the submitted data
res
.
write
(
"
Website name:
"
body
.
name
)
;
res
.
write
(
"
"
)
;
res
.
write
(
"
Website URL:
"
body
.
url
)
;
}
else
{
//
Output the form
res
.
write
(
postHTML
)
;
}
res
.
end
(
)
;
}
)
;
}
)
.
listen
(
3000
)
;
Execution result Gif demonstration:
