In many scenarios, our server needs to interact with the user's browser, such as form submissions.
Form submissions to the server typically use GET/POST requests.
This chapter will introduce Node.js GET/POST requests.
* * *
## Obtaining GET Request Content
Since GET requests are directly embedded in the path, the URL is the complete request path, including the part after the `?`. Therefore, you can manually parse the content after the `?` as GET request parameters.
In Node.js, you can use the URL constructor to parse the requested 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 various components of a URL, such as the protocol, hostname, path, query parameters, etc.
## Example
```javascript
const http = require('http');
const util = require('util');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
const myUrl = new URL(req.url, `http://${req.headers.host}`);
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)
}));
}).listen(3000);
console.log("Server is running at http://localhost:3000");
Visit ** in your browser and check the returned result:
!(#)
### Getting URL Parameters
We can use the `url.parse` method to parse parameters in the URL, as shown in the following code:
## Example
```javascript
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
const myUrl = new URL(req.url, `http://${req.headers.host}`);
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");
Visit ** in your browser and check the returned result:
!(#)
### URL Object
The following are the properties and methods of the URL object:
| Property/Method | Description | Example Output |
| --- | --- | --- |
| **href** | The full URL string | `"http://example.com:8080/path?foo=bar#section"` |
| **origin** | The origin of the URL, including protocol, hostname, and port (if present) | `"http://example.com:8080"` |
| **protocol** | The protocol part of the URL, followed by `:` | `"http:"` |
| **host** | The hostname and port number | `"example.com:8080"` |
| **hostname** | The hostname, without the port number | `"example.com"` |
| **port** | The port number (if specified) | `"8080"` |
| **pathname** | The pathname part | `"/path"` |
| **search** | The query string part, including the leading `?` | `"?foo=bar&hello=world"` |
| **searchParams** | The `URLSearchParams` object for manipulating query parameters | `{ foo: 'bar', hello: 'world' }` |
| **hash** | The fragment part, including the `#` | `"#section"` |
| Method | Description | Example Code | Example Output |
| --- | --- | --- | --- |
| **get(name)** | Get the value of a query parameter by 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 a query parameter by name (updates if it exists) | `myUrl.searchParams.set("foo", "newBar")` | `?foo=newBar` |
| **delete(name)** | Delete a query parameter by name | `myUrl.searchParams.delete("foo")` | `?hello=world` |
| **has(name)** | Check if a query parameter exists by name | `myUrl.searchParams.has("foo")` | `true` or `false` |
| **forEach(callback)** | Iterate over key-value pairs of query parameters, executing a callback function | `myUrl.searchParams.forEach((v, k) => console.log(k, v))` | Key-value pair output |
| **toString()** | Convert query parameters to a string format, suitable for reconstructing the URL | `myUrl.searchParams.toString()` | `"foo=bar&hello=world"` |
## Example
```javascript
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
* * *
## Obtaining POST Request Content
In Node.js, handling POST requests typically requires using the `http` module to receive data in the request body. Unlike GET requests, POST request data is not included in the URL but 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 on the request object.
* **Listen for the `data` event**: When a chunk of data arrives at the server, the `data` event is triggered, and the data chunk is passed as an argument to the callback.
* **Listen for the `end` event**: When the entire request body has been received, the `end` event is triggered, at which point you can process the complete POST data.
The following code demonstrates how to use the `http` module in Node.js to handle POST requests:
## Example
```javascript
const http = require('http');
// Create HTTP server
http.createServer((req, res) => {
// Check if the request method is POST
if (req.method === 'POST') {
let body = '';
// Listen for the 'data' event to receive data chunks
req.on('data', (chunk) => {
body += chunk; // Accumulate received data chunks
});
// Listen for the 'end' event when data reception is complete
req.on('end', () => {
// Output the received POST data
console.log('Received POST data:', body);
// Set response headers and content
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('POST data received successfully!');
});
} else {
// Handle 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:**
1. **Check Request Method**: Determine if the request type is POST using `req.method === 'POST'`.
2. **Receive Data**: Accumulate data chunks in the `req.on('data')` event to form the complete data body.
3. **Complete Reception**: Process the complete POST data in the `req.on('end')` event.
4. **Respond to Client**: After receiving and processing the data, send a response to the client.
You can use the `curl` command to test the POST request:
```bash
curl -X POST -d "name=example&age=25" http://localhost:3000
### Handling JSON Data
If the POST request sends JSON data, you can parse the received data into an object in `req.on('end')`:
```javascript
req.on('end', () => {
const parsedData = JSON.parse(body); // Parse JSON string into an object
console.log('Received JSON data:', parsedData);
res.end('JSON data received successfully!');
});
### The querystring Module
The `querystring` module is used for handling 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.
Assuming the client sends POST request data in the `application/x-www-form-urlencoded` format (e.g., form submission), the data format is 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
```javascript
var http = require('http');
var querystring = require('querystring');
var util = require('util');
http.createServer(function(req, res){
var post = '';
req.on('data', function(chunk){
post += chunk;
});
req.on('end', function(){
post = querystring.parse(post);
res.end(util.inspect(post));
});
}).listen(3000);
The following example submits a form via POST and outputs the data:
## Example
```javascript
var http = require('http');
var querystring = require('querystring');
var postHTML =
'' +
'' +
'' +
'Website Name:
' +
'Website URL:
' +
'' +
'' +
'';
http.createServer(function(req, res){
var body = "";
req.on('data', function(chunk){
body += chunk;
});
req.on('end', function(){
body = querystring.parse(body);
res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
if(body.name && body.url){
res.write("Website Name: " + body.name);
res.write("
");
res.write("Website URL: " + body.url);
} else {
res.write(postHTML);
}
res.end();
});
}).listen(3000);
Execution result GIF demonstration:
!(#)
π Categories
- β‘ JavaScript (1589)
- π PHP (872)
- π Python3 (810)
- π HTML (691)
- βοΈ C# (650)
- π Python (594)
- β Java (552)
- βοΈ PyTorch (534)
- π§ Linux (472)
- βοΈ C (432)
- π¦ jQuery (406)
- π¨ CSS (377)
- π XML (259)
- π¦ jQuery UI (231)
- π― Bootstrap (220)
- βοΈ C++ (215)
- π °οΈ Angular (205)
- π HTML DOM (201)
- π΄ Redis (188)
- π Web Building (142)
- π Vue.js (141)
- π R (131)
- πΌ Pandas (124)
- ποΈ SQL (105)
- βοΈ Docker (86)
- βοΈ TypeScript (73)
- βοΈ Highcharts (70)
- π AI Agent (70)
- βοΈ React (68)
- π Node.js (65)
- βοΈ Machine Learning (60)
- π Git (59)
- π΅ Go (58)
- π Markdown (58)
- π’ NumPy (55)
- π§ͺ Flask (54)
- βοΈ Scala (53)
- ποΈ SQLite (52)
- π JSTL (52)
- βοΈ VS Code (51)
- π MongoDB (49)
- π Perl (48)
- π Ruby (47)
- π Matplotlib (47)
- βοΈ Uncategorized (46)
- π Swift (46)
- ποΈ PostgreSQL (46)
- βοΈ Data Structures (46)
- π Playwright (46)
- π iOS (45)
- ποΈ MySQL (44)
- βοΈ LangChain (43)
- π FastAPI (40)
- βοΈ Ionic (38)
- π Design Patterns (37)
- βοΈ Eclipse (37)
- π¨ CSS3 (34)
- π Lua (34)
- βοΈ Codex (34)
- πΈ Django (32)
- βοΈ OpenCV (32)
- π Rust (31)
- π JSP (31)
- βοΈ Claude Code (31)
- π Pillow (30)
- βοΈ OpenCode (28)
- π AI Skills (27)
- π Flutter (26)
- π Maven (26)
- π¨ Tailwind CSS (25)
- π§ TensorFlow (25)
- π Servlet (24)
- π Dart (23)
- π Assembly (23)
- βοΈ Memcached (22)
- βοΈ SVG (22)
- βοΈ Electron (22)
- π NLP (22)
- π Regex (21)
- π Android (20)
- π£ Kotlin (19)
- π Julia (19)
- π SOAP (17)
- π Selenium (17)
- π PowerShell (17)
- π Sass (16)
- π HTTP (16)
- π Zig (15)
- π AI (15)
- π AJAX (14)
- π Swagger (14)
- βοΈ Scikit-learn (13)
- βοΈ ECharts (13)
- βοΈ Chart.js (13)
- βοΈ Cursor (13)
- βοΈ SciPy (12)
- π RDF (12)
- π Ollama (12)
- π Next.js (12)
- π Plotly Dash (12)
- π JSON (11)
- π RESTful API (11)
- π WSDL (9)
- βοΈ CMake (8)
- π Firebug (7)
- π Nginx (6)
- βΈοΈ Kubernetes (6)
- π Jupyter (6)
- π LaTeX (4)
- π UniApp (4)
- ποΈ SQL Server (1)
YouTip