简体   繁体   English

我们可以在 Express.js 的路由中使用另一个路由吗?

[英]Can we use another route within a route in Express.js?

So I have index.js, userRoute, and friendRoute所以我有 index.js、userRoute 和friendRoute

in index.js在 index.js 中

const app = express()
const userRoutes = require('./routes/user')
app.use('/users', userRoutes)

in /routes/user.js, I want to append /friends routes在 /routes/user.js 中,我想附加 /friends 路线

const friendRoutes = require('../routes/friend')
router.use('/:username/friends', friendRoutes)

The expected result that I want is get the user's list of friends /users/:username/friends我想要的预期结果是获取用户的好友列表/users/:username/friends

But I didn't get the username params when I tried to hit the url Is there any way to achieve the expected result?但是当我尝试点击url时没有得到用户名参数有什么办法可以达到预期的结果? or is there best practice of doing this kind of stuff?或者有做这种事情的最佳实践吗?

exports.friendRoutes = async (req, res)=>{
    const username = req.params.username;
    console.log(username)
}

// or

exports.friendRoutes = async (req, res)=>{
    const {username} = req.params;
    console.log(username)
}
Update your /routes/user.js 更新您的 /routes/user.js
 const friendRoutes = require('../routes/friend') router.use('/:username/friends', (req, res, next) => { req.username = req.params.username; next(); }, friendRoutes);
Use req.username in your /routes/friend.js to get the params value 在 /routes/friend.js 中使用 req.username 来获取 params 值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM