如何在Express.js中过滤路由路径
Express.js是一个强大的node.js框架。这个框架的主要优势之一是定义不同的路由或中间件来处理客户端的不同的传入请求。在本文中,我们将讨论如何使用node.js中的express.js来过滤路由的路径。
app.use() 方法用于处理不同的节点的请求以过滤特定路由。该函数用于在被指定的路径上挂载指定的中间件函数。它主要用于为您的应用程序设置中间件。
语法:
app.use(path, callback)
参数:
此方法接受以下两个参数:
- path: 中间件函数调用的路径。可以是表示路径或路径模式的字符串,也可以是要匹配路径的正则表达式模式。
- callback: 中间件函数或中间件函数的系列/数组。
安装模块:
使用以下命令安装所需模块。
npm install express
项目结构: 将会是这样的。
注意: Home.js和login.js文件存在于 routes 文件夹中。
Home.js
// Importing express module
const express = require("express")
const router = express.Router()
// Handling request using router
router.get("/home", (req, res, next) => {
res.send("This is the homepage request")
})
// Exporting the router
module.exports = router
login.js
// Importing the module
const express = require("express")
// Creating express Router
const router = express.Router()
// Handling login request
router.get("/login", (req, res, next) => {
res.send("This is the login request")
})
// Exporting the router
module.exports = router
index.js
// Requiring module
const express = require("express")
// Importing all the routes
const homeroute = require("./routes/Home.js")
const loginroute = require("./routes/login")
// Creating express server
const app = express()
// Filtering the routes path
app.use("/", homeroute)
app.use("/", loginroute)
// Server setup
app.listen((3000), () => {
console.log("Server is Running")
})
使用以下命令运行 index.js 文件:
node index.js
输出: 现在打开你的浏览器并跳转到 http://localhost:3000/home ,你将看到以下输出: