【问题标题】:How to create a custom path in URL using nodeJS/expressJS如何使用 nodeJS/expressJS 在 URL 中创建自定义路径
【发布时间】:2020-04-21 02:33:21
【问题描述】:

我希望能够创建自定义路径。例如,如果用户单击按钮 [创建房间],浏览器会将用户重定向到:http://www.example.com/[room_id]/index.html

有没有办法实现这个?用户将提交一个带有按钮的表单。类似的东西。

基本上这就是我所拥有的

index.html

<form method='POST' name='path_id' id='clickedButtom'>

    <input id="pickName" class="center-align" type='text'>
    <input id='rea2dy' value=" Ready >" type='submit'>      

</form>

server.js

app.get('path_id', function(req, res) {
    res.send('hello');
});
//I was the path_id to be a random string of letters and numbers basically

【问题讨论】:

  • 如果有后端服务器处理表单,可以通过将用户重定向到您想要的 URL 来完成
  • 我不确定我是否理解,我更新了问题以提供更多见解
  • 我的意思是在后端你可以做res.redirect('http://your.site/custom/path')
  • 我明白了,这是有道理的。谢谢你:)

标签: node.js express socket.io routes


【解决方案1】:

对于您正在谈论的所有 URL,您可以像这样提前定义一个 Express 路由,该路由将在路由中包含代码以查看房间 ID 并采取相应措施:

app.post('/createRoom, (req, res) => {
     // do whatever you do here to create the room data structure on the server
    // and assign it an ID
    let roomID = ...;
    res.redirect(`/${roomID}/index.html`);
});

app.get('/:roomID/index.html', (req, res) => {
    let roomID = req.params.roomID;
    // now render whatever you want the user to see for this particular room
    res.send(...);
});

【讨论】:

  • @pylot - 这能回答你的问题吗?如果是这样,您可以通过单击答案左侧的复选标记向社区表明这一点,并在此处为自己赢得一些声誉积分以遵循正确的程序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-04
  • 1970-01-01
  • 1970-01-01
  • 2014-09-06
  • 2021-03-16
相关资源
最近更新 更多