Home >Web Front-end >Front-end Q&A >nodejs set routing
With the rapid development of front-end technology, more and more people are paying attention to back-end development. As a lightweight back-end framework, Node.js has been recognized and used by more and more developers.
In Node.js, setting routing is a very important part. Routing determines which handler a request should be handled by. This article details how to set up routing.
1. Install Node.js
Before starting to set up routing, we need to install Node.js first. Node.js can be downloaded and installed on the official website.
After the installation is complete, enter the following command on the command line to check the version of Node.js:
node -v
2. Create the server.js file
In Node.js , we need to create a server.js file to start the server and set up routing. In this file, we need to introduce the http module and create a server instance.
The following is a basic server.js file:
const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World! '); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
In the above file, we created a server instance and set the server's IP address and port number. We also added a processing function to this server to send a "Hello, World!" response when a request comes in.
You can use the following command to start the server in the command line:
node server.js
3. Set routing
The main purpose of setting routing is to let the server The corresponding handler can be called according to the requested path.
In order to achieve this purpose, we need to define a routing table. A routing table is an object where the keys are the paths of requests and the values are handler functions.
The following is a simple routing table:
const routes = { '/': homeHandler, '/about': aboutHandler, '/contact': contactHandler };
In this routing table, we define three paths: '/', '/about' and '/contact'. Each path is associated with a handler function.
Next, we need to define the handler. A handler is a function that handles different requests. For example, a handler can send an HTML page, read a database, or call an API.
The following is a simple handler:
const homeHandler = (req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/html'); res.end('<h1>Welcome to my homepage!</h1>'); }; const aboutHandler = (req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/html'); res.end('<h1>About me</h1><p>I am a Node.js developer.</p>'); }; const contactHandler = (req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/html'); res.end('<h1>Contact me</h1><p>You can contact me at nodejs@example.com.</p>'); };
Each handler sets the HTTP status code, response headers, and response body so that when the request arrives, the request can be processed correctly.
Now, we need to connect the routing table with the handler. We can add a routing function to the server creation function to implement routing processing.
The following is a complete route handling code:
const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const routes = { '/': homeHandler, '/about': aboutHandler, '/contact': contactHandler }; const homeHandler = (req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/html'); res.end('<h1>Welcome to my homepage!</h1>'); }; const aboutHandler = (req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/html'); res.end('<h1>About me</h1><p>I am a Node.js developer.</p>'); }; const contactHandler = (req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/html'); res.end('<h1>Contact me</h1><p>You can contact me at nodejs@example.com.</p>'); }; const server = http.createServer((req, res) => { const url = req.url; if (routes[url]) { routes[url](req, res); } else { res.statusCode = 404; res.setHeader('Content-Type', 'text/plain'); res.end('404 - Not found'); } }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
In this code, we connect the routing table with the handler. When a request arrives, we match the request's path against the routing table. If the match is successful, we call the appropriate handler. If there is no match, we will send a 404 error in response.
4. Summary
In Node.js, setting routing is a very important part. Routing is the key factor in deciding which handler a request should be handled by.
This article details how to set up routing. By reading this article, readers can understand how to create servers, define routing tables and handlers, and connect them.
Node.js, as a flexible and easy-to-learn back-end framework, is of great help in improving development efficiency and developer skill levels.
The above is the detailed content of nodejs set routing. For more information, please follow other related articles on the PHP Chinese website!