遵义微商城网站建设平台,wordpress 优惠券 插件,吴中区企业网络推广,网站如何设置默认首页中间件#xff08;express#xff09;
在Express.js中#xff0c;中间件#xff08;Middleware#xff09;是一个重要的组成部分#xff0c;用于处理HTTP请求和响应。中间件函数具有特定的签名#xff0c;并可以接受请求对象#xff08;req#xff09;、响应对象express
在Express.js中中间件Middleware是一个重要的组成部分用于处理HTTP请求和响应。中间件函数具有特定的签名并可以接受请求对象req、响应对象res以及一个可选的next函数作为参数。
中间件函数可以对请求和响应对象执行各种任务例如执行身份验证、解析数据、压缩响应等。如果中间件函数没有结束请求-响应循环例如没有调用res.end()或res.send()那么它应该调用next()函数将控制权传递给下一个中间件。 下面是一个Express中间件的基本示例
const express require(express);
const app express(); // 中间件函数
function logger(req, res, next) { console.log(Logging:, req.method, req.url); next(); // 调用下一个中间件
} // 另一个中间件函数用于检查用户是否已登录
function authenticate(req, res, next) { // 假设我们有一个检查用户是否已登录的方法 const isAuthenticated req.isAuthenticated(); // 伪代码 if (isAuthenticated) { next(); // 用户已登录继续处理 } else { res.status(401).send(Unauthorized); // 用户未登录返回401状态码 }
} // 路由处理程序
function homePage(req, res) { res.send(Home Page);
} // 使用中间件
app.use(logger); // 应用于所有请求 // 特定路由的中间件
app.get(/protected, authenticate, homePage); // 先进行身份验证再访问主页 // 未保护的路由
app.get(/, homePage); // 直接访问主页 // 启动服务器
app.listen(3000, () { console.log(Server started on port 3000);
});**1内置中间件**使用中间件设置静态文件的路径及访问javascript
app.use(express.static(path.join(__dirname,quot;./publicquot;)))2自定义中间件
app.use((req,res,next)gt;{if(req.urlquot;/quot;){res.end(quot;indexquot;)//index.html文件}else{next()}
})
app.use((req,res,next)gt;{if(req.urlquot;/listquot;){res.end(quot;listquot;)//list.html文件}else{next()}
})app.use((req,res,next)gt;{if(req.urlquot;/orderquot;){res.end(quot;orderquot;)//order.html文件}
})3第三方中间件 使用官网资源中的中间件》》》body-parser
cnpm install body-parser -s代码
const bodyParse require(quot;body-parserquot;);app.use(express.static(path.join(__dirname, quot;./publicquot;)))
app.use(bodyParse.urlencoded({ extended: false }))使用post
app.post(quot;/listquot;,(req,res)gt;{let{username,age}req.body;res.json({username,age})
})使用get
app.get(quot;/userquot;, (req, res) gt; {let { username, age } req.body;console.log({ username, age });res.json({username,age})})4路由中间件
在这个例子中logRequest中间件被应用于所有路由因为我们将它添加为应用程序级别的中间件使用app.use()。然后我们定义了一个路由/并附加了一个处理程序homePage。当有人访问/路由时他们首先会触发logRequest中间件然后才会触发homePage处理程序。
const express require(express);
const app express(); // 这是一个简单的中间件函数用于记录每个请求的URL
function logRequest(req, res, next) { console.log(Request URL: ${req.url}); next(); // 调用下一个中间件或路由处理程序
} // 这是一个路由处理程序
function homePage(req, res) { res.send(Home Page);
} // 使用中间件函数
app.use(logRequest); // 这个中间件将应用于所有路由 // 定义路由并附加处理程序
app.get(/, homePage); // 启动服务器
app.listen(3000, () { console.log(Server started on port 3000);
});