YouTip LogoYouTip

Node Js Get Post

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: !(#)
← Php Echo PrintLinux User Manage β†’