![](/img/trans.png)
[英]Nodejs - How to route by name in url with express and mongoose?
[英]How to extract page name and authToken from url using express get route in nodejs?
我有 URL 像这样: http://localhost:3000/pageName
我正在设置我的快速路线,如下所示:
app.get("/:pageName",(req,res)=>{
if (authentication === true) {
res.render(req.param.pageName}
})
当它得到http://localhost:3000/demo
时,上面的工作正常。
但是,当它获得这种类型的 URL: http://localhost:3000/pageName/authToken
时,例如:
http://localhost:3000/demo/ubawfei346876jhat78gw8898ig8837yr
路线说无法获得demo/ubawfei346876jhat78gw8898ig8837yr
,当我将上面的代码更改为:
app.get("/:pageName/: authToken",(req,res) => {
if(authentication===true{
res.render(req.param.pageName}
)}
然后这种类型的 url 工作正常: http://localhost:3000/demo/ubawfei346876jhat78gw8898ig8837yr
但是这种类型的 URL: http://localhost:3000/demo
不再工作了
当 url 是这样的时候,我想实现这样的东西
http://localhost:3000/demo
然后它应该重定向到:
req.params.pageName
当 url 看起来像这样http://localhost:3000/demo/yeieyhsi736hdh
那么它应该改变令牌,如果 varified 重定向到:
req.params.pageName
您可以实现这两个路由,如果提供了authToken
,则对authToken
运行检查。
但是,您现在执行此操作的方式会导致无休止的重定向,因为当对您的/:pageName
发出任何请求时,它将被重定向到自身,因此您需要从路由中提供包含内容的response
,不是redirect
。
app.get("/:pageName", (req, res) => {
if (authentication) {
let pageName = req.params.pageName;
//Retrieve something with pageName and send it;
res.send(pageName);
} else {
res.send("Not authorised");
}
})
app.get("/:pageName/:authToken", (req, res) => {
let authToken = req.params.authToken;
if (isGood(authToken) && authentication) { //Fictious authToken check
let pageName = req.params.pageName;
//Retrieve something with pageName and send it;
res.send(pageName);
} else {
res.send("Not authorised");
}
})
让你的 url 像这样http://localhost:3000/demo?token=As3ferrfmi5jr4jr4btdth54y6y6rty34t45t5y666666
app.get('/:pageName', (req, res) => {
//you can check if pageName is correct or not
if (req.query.token != undefined) {
const token = req.query.token;
// we must use strong secret, I am using "secret" for demo
jwt.verify(token,"secret", (err,data) => {
if (err) {
//do something if error occurs
} else {
// you can also do something with data which was stored on your token
res.render(req.params.pageName);
}
})
} else if (authenticate) {
// do something for authentication to access this else if
res.render(req.params.pageName);
} else {
// you can also render some error page or send 404 status
res.send('Something went wrong!');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.