简体   繁体   English

node js express 使用带有创建名称的 app.get 重定向到它

[英]node js express use app.get with created name to redirect to it

I have code below.我有下面的代码。 We post room name with ajax to url /room-api我们用 ajax 到 url /room-api 发布房间名称

function getCreatedRoomName(x){

  $.ajax({
    type: "POST",
    url: "/room-api",
    data: { roomname: x },
    success: function(data) {
    },
    error: function(jqXHR, textStatus, err) {
    alert('text status '+textStatus+', err '+err)
    }
    });

  return x;
}

app.js应用程序.js

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


var room_name;

app.post('/room-api', isLoggedIn, function(req, res){
  room_name = req.body.roomname;
  console.log(room_name);
});

Then we receive that data with app.post as you can see above.然后我们通过 app.post 接收该数据,如上所示。 How can I create a new app.get with created name?如何使用创建的名称创建新的 app.get? I tried this.我试过这个。

app.post('/room-api', isLoggedIn, function(req, res){
  room_name = req.body.roomname;

  app.get(`/${room_name}`, isLoggedIn, function(req, res){
      res.redirect(`/${room_name}`);
  });

  console.log(room_name);
});

But it doesn't work.但它不起作用。

It won't work, becase the routes are declared at the app level (this one is undefined, then), ie they're static, once the app has started, they can't be added dynamically.它不会起作用,因为路由是在应用程序级别声明的(然后这是未定义的),即它们是 static,一旦应用程序启动,它们就不能动态添加。

Dynamic endpoints are usually handled by using route parameters.动态端点通常使用路由参数来处理。

Check Route parameters :检查路线参数

Route parameters are named URL segments that are used to capture the values http://expressjs.com/en/guide/routing.html#route-parameters路由参数命名为 URL 段,用于捕获值http://expressjs.com/en/guide/routing.html#route-parameters

In your case, try creating a route that will handle room names, and pass it room name as a URL parameter:在您的情况下,尝试创建将处理房间名称的路由,并将房间名称作为 URL 参数传递:

app.get('/room/:room_name', isLoggedIn, function(req, res){
    
    console.log('the room_name is in req.params', req.params);
    res.redirect(req.params.room_name);

});

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

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