Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js Routing

Node.js Routing

In Node.js, routing is a key part of handling HTTP requests; it determines how requests are dispatched according to different URLs and HTTP methods (such as GET, POST, PUT, DELETE, etc.).

Routing is commonly used to build web applications, especially RESTful APIs.

Node.js itself has no built-in routing mechanism, but routing can be implemented through middleware libraries such as Express.

Routing typically involves the following aspects:

In Node.js, we can create a simple router using the http module, as shown in the following example:

Example

const

http

=

require

(

'http'

)

;

// Create a server and define routes

const

server

=

http.

createServer

(

(

req

,

res

)

=>

{

 

const

{

url

,

method

}

=

req

;

 

if

(

url

===

'/'

&&

method

===

'GET'

)

{

    res.

writeHead

(

200

,

{

'Content-Type'

:

'text/plain'

}

)

;

    res.

end

(

'Home Page'

)

;

 

}

else

if

(

url

===

'/about'

&&

method

===

'GET'

)

{

    res.

writeHead

(

200

,

{

'Content-Type'

:

'text/plain'

}

)

;

    res.

end

(

'About Page'

)

;

 

}

else

{

    res.

writeHead

(

404

,

{

'Content-Type'

:

'text/plain'

}

)

;

    res.

end

(

'404 Not Found'

)

;

 

}

}

)

;

server.

listen

(

3000

,

(

)

=>

{

  console.

log

(

'Server is running on http://localhost:3000'

)

;

}

)

;

Access in the browser http://localhost:3000 The display is as follows:

Access in the browser http://localhost:3000/about The display is as follows:

If you visit another URL, it will simply display 404 Not Found。

For more information on HTTP requests, see:HTTP Tutorial。


Request parameters

A complete URL such as http://localhost:8888/start?foo=bar&hello=world contains a host, a path, and a query string.

To parse this data, we can use the URL object and the querystring module.

const myUrl = new URL("http://localhost:8888/start?foo=bar&hello=world");



// Extract path name

console.log(myUrl.pathname); // 输出: /start



// Extract query parameters

console.log(myUrl.searchParams.get("foo"));   // 输出: bar

console.log(myUrl.searchParams.get("hello")); // 输出: world



myUrl.pathname

          |

          |

        -----

http://localhost:8888/start?foo=bar&hello=world

                                ---       -----

                                 |          |

                                 |          |

           myUrl.searchParams.get("foo")    |

                                            |

                                     myUrl.searchParams.get("hello")

Of course, we can also use the querystring module to parse parameters in the POST request body; this will be covered in the following Node.js GET/POST Requests section.

All the request data we need is contained in the request object, which is passed as the first argument to the onRequest() callback function.

Now let's add some logic to the http module's onRequest() function to find out the URL path requested by the browser:

server.js file code:

var

http

=

require

(

"

http

"

)

;

var

url

=

require

(

"

url

"

)

;

function

start

(

)

{

function

onRequest

(

request

,

response

)

{

//

Parse the request path using the URL constructor

const

pathname

=

new

URL

(

request

.

url

, `

http

:

//

${request.headers.host}`).pathname;

console

.

log

(

`

Request

for

$

{

pathname

}

received

.`

)

;

//

Print the request path

//

Set response headers and content

response

.

writeHead

(

200

,

{

"

Content-Type

"

:

"

text/plain

"

}

)

;

//

Set the status code and content type

response

.

write

(

"

Hello World

"

)

;

//

Send the response content to the client

response

.

end

(

)

;

//

End the response

}

//

Create a server and listen on the specified port

http

.

createServer

(

onRequest

)

.

listen

(

8888

)

;

console

.

log

(

"

Server has started.

"

)

;

//

Print the server startup message

}

//

Export the start function for use by other modules

module

.

exports

.

start

=

start

;

Now our application can distinguish different requests by their URL path—this allows us to use routing (not yet complete) to map requests to handlers based on the URL path.

In the application we are building, this means requests from /start and /upload can be handled by different code. We will see later how these pieces fit together.

Now we can write the router by creating a file named router.js router.js and adding the following content:

The router.js file code:

function

route

(

pathname

)

{

console

.

log

(

"

About to route a request for

"

pathname

)

;

}

//

Export the route function

exports

.

route

=

route

;

router.js handles the routing logic; it defines and exports the route function, used to handle different paths when the server receives a request.

Our server should be aware of the router and use it effectively. We could certainly hard-code this dependency into the server, but experience with other programming languages tells us this would be painful, so we will use dependency injection to add the router module in a loosely coupled way.

First, let's extend the server's start() function so that the route function can be passed in as a parameter,server.js the file code is as follows:

server.js file code:

//

server.js

const

http

=

require

(

"

http

"

)

;

//

Import Node.js's http module to create the server

const

{

URL

}

=

require

(

"

url

"

)

;

//

Import the URL constructor from the url module

//

Define and export the start function to start the server

function

start

(

route

)

{

//

Define the onRequest function to handle each request

function

onRequest

(

request

,

response

)

{

//

Parse the request path using the URL constructor

const

pathname

=

new

URL

(

request

.

url

, `

http

:

//

${request.headers.host}`).pathname;

console

.

log

(

`

Request

for

$

{

pathname

}

received

.`

)

;

//

Print the request path

route

(

pathname

)

;

//

Call the route function to handle the path

//

Set response headers and content

response

.

writeHead

(

200

,

{

"

Content-Type

"

:

"

text/plain

"

}

)

;

response

.

write

(

"

Hello World

"

)

;

response

.

end

(

)

; }

//

Create a server and listen on the specified port

http

.

createServer

(

onRequest

)

.

listen

(

8888

)

;

console

.

log

(

"

Server has started.

"

)

; }

//

Export the start function for use by other modules

module

.

exports

.

start

=

start

;

server.js defines the server startup logic and calls the route function when a request is received.

At the same time, we will extend index.js accordingly so that the route function can be injected into the server:

The index.js file code:

var

server

=

require

(

"

./server

"

)

;

var

router

=

require

(

"

./router

"

)

;

server

.

start

(

router

.

route

)

;

index.js is the program's entry file, responsible for starting the server and passing the router module into the server module.

Now start the application (node index.js—always remember this command line), then request a URL. You will see the application print the corresponding message, which means our HTTP server is using the router module and passing the requested path to the router:



$ node index.js

Server has started.

Access in the browser http://localhost:8888/The server should print a routing-related message for the path in the console and return a "Hello World" response:

The background terminal will display the access information:

Request for / received.

About to route a request for /

Request for /favicon.ico received.

About to route a request for /favicon.ico


Routing with Express

Express is a popular Node.js framework that provides powerful routing capabilities.

For more about Express, see:Node.js Express Framework。

Installing Express

First, make sure Express is installed; if not, you can install it using npm:



npm install express

Basic routing

The following is a simple Express application that shows how to set up basic routing:

Example

const

express

=

require

(

'express'

)

;

const

app

=

express

(

)

;

const

port

=

3000

;

// Define a GET route

app.

get

(

'/'

,

(

req

,

res

)

=>

{

    res.

send

(

'Hello, World!'

)

;

}

)

;

// Define a POST route

app.

post

(

'/submit'

,

(

req

,

res

)

=>

{

    res.

send

(

'Form submitted!'

)

;

}

)

;

// Start the server

app.

listen

(

port

,

(

)

=>

{

    console.

log

(

`Server is running on http

:

//localhost:${port}`);

}

)

;

Dynamic Route

Dynamic routing lets you use parameterized URLs.

For example, you can define a route to handle /users/:id, where :id is a dynamic parameter.

app.get('/users/:id', (req, res) => {

    const userId = req.params.id;

    res.send(`User ID: ${userId}`);

});

Route parameters

Express lets you extract parameters from the URL and access them through the req.params object.

Example

app.

get

(

'/users/:id'

,

(

req

,

res

)

=>

{

   

const

userId

=

req.

params

.

id

;

    res.

send

(

`User ID

:

$

{

userId

}

`

)

;

}

)

;

app.

get

(

'/search/:query'

,

(

req

,

res

)

=>

{

   

const

query

=

req.

params

.

query

;

    res.

send

(

`Search query

:

$

{

query

}

`

)

;

}

)

;

Query Parameters

Query parameters are key-value pairs in the URL, usually used to pass additional information. You can access query parameters through the req.query object.

app.get('/search', (req, res) => {

    const query = req.query.q;

    res.send(`Search query: ${query}`);

});

Route middleware

Route middleware is a function executed before or after a request is handled. You can use middleware for tasks such as authentication and logging.

// 日志记录中间件

const logger = (req, res, next) => {

    console.log(`Request Type: ${req.method} ${req.url}`);

    next();

};



// Use middleware

app.use(logger);



app.get('/', (req, res) => {

    res.send('Hello, World!');

});

Route grouping

To organize code better, you can use route grouping. Express provides the express.Router object, which can be used to create modular, mountable route handlers.

Example

const

express

=

require

(

'express'

)

;

const

app

=

express

(

)

;

const

port

=

3000

;

// Create a router instance

const

userRouter

=

express.

Router

(

)

;

// Define user-related routes

userRouter.

get

(

'/'

,

(

req

,

res

)

=>

{

    res.

send

(

'List of users'

)

;

}

)

;

userRouter.

get

(

'/:id'

,

(

req

,

res

)

=>

{

   

const

userId

=

req.

params

.

id

;

    res.

send

(

`User ID

:

$

{

userId

}

`

)

;

}

)

;

// Mount the user router

app.

use

(

'/users'

,

userRouter

)

;

// Start the server

app.

listen

(

port

,

(

)

=>

{

    console.

log

(

`Server is running on http

:

//localhost:${port}`);

}

)

;

Advanced routing techniques

1. Error handling: You can define error-handling middleware to catch and handle errors in routes.

app.use((err, req, res, next) => {

    console.error(err.stack);

    res.status(500).send('Something broke!');

});

**2. Route priority:** the order in which routes are defined determines their priority; routes defined first are matched first.

3. Route restrictions: You can use middleware to restrict access to certain routes, for example, allowing only authenticated users.

Example

const

authMiddleware

=

(

req

,

res

,

next

)

=>

{

   

if

(

req.

headers

.

authorization

)

{

        next

(

)

;

   

}

else

{

        res.

status

(

401

)

.

send

(

'Unauthorized'

)

;

   

}

}

;

app.

get

(

'/admin'

,

authMiddleware

,

(

req

,

res

)

=>

{

    res.

send

(

'Admin page'

)

;

}

)

;