Home >Web Front-end >Front-end Q&A >How to use Node.js to listen for requests
Node.js is a very popular server-side JavaScript environment. One of its main advantages is its ability to efficiently handle large numbers of concurrent requests. In this article, we will introduce how to use Node.js to listen for requests.
To use Node.js to listen for requests, we first need to create a server. In Node.js, servers can be created through the built-in http
module. Here is a simple server example:
const http = require("http"); const server = http.createServer((req, res) => { res.writeHead(200, { "Content-Type": "text/plain" }); res.write("Hello, World!"); res.end(); }); server.listen(3000, () => { console.log("Server listening on port 3000"); });
In this example, we create a server and listen for requests on port 3000. When a request is received, the server will return an HTTP response containing a "Hello, World!" message.
Now we can start the server and access it using a browser. Just type http://localhost:3000
into your browser and you'll see the "Hello, World!" message. It means that the server is working normally and has been listening for requests.
Let’s look at a few examples of using Node.js to listen for requests in action.
First example:
const http = require("http"); const server = http.createServer((req, res) => { if (req.method === "GET" && req.url === "/") { res.writeHead(200, { "Content-Type": "text/plain" }); res.write("Hello, World!"); res.end(); } else { res.writeHead(404, { "Content-Type": "text/plain" }); res.write("404 Not Found"); res.end(); } }); server.listen(3000, () => { console.log("Server listening on port 3000"); });
In this example, we only processed GET requests and only accepted requests from the root path/
request. If the requested URL is not /
, a 404 Not Found error is returned.
If you want to process POST requests, you need to use Node.js's built-in querystring
module to parse the data in the request body. Here is a simple example:
const http = require("http"); const qs = require("querystring"); const server = http.createServer((req, res) => { if (req.method === "POST" && req.url === "/") { let body = ""; req.on("data", (chunk) => { body += chunk; }); req.on("end", () => { const data = qs.parse(body); res.writeHead(200, { "Content-Type": "text/plain" }); res.write(`Hello, ${data.name}!`); res.end(); }); } else { res.writeHead(404, { "Content-Type": "text/plain" }); res.write("404 Not Found"); res.end(); } }); server.listen(3000, () => { console.log("Server listening on port 3000"); });
In this example, we process the POST request and parse the data in the request body. In the response, we used the name from the request body to create a personalized message.
In actual applications, we usually provide static file services on the Node.js server. To do this, we can use the express
framework and the serve-static
module to enable static file serving. Here is an example using express
and serve-static
:
const express = require("express"); const serveStatic = require("serve-static"); const app = express(); app.use(serveStatic("public", { index: false })); const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server listening on http://localhost:${port}`); });
In this example, we specify the directory where the static files to be served are located (in this In the example, it is the public
directory) and passes it to the serve-static
middleware. We then add the middleware to the app
instance. Now, we can create a static file service using express
and listen for requests on port 3000.
The above are a few examples of listening for requests and handling them in Node.js. Different application scenarios require different methods. By using the built-in HTTP module of Node.js, we can easily create a server to listen for requests, and through some middleware we can also easily handle different types of requests. We hope these examples help you understand how to listen for requests in Node.js.
The above is the detailed content of How to use Node.js to listen for requests. For more information, please follow other related articles on the PHP Chinese website!