I have code below. We post room name with ajax to 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
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. How can I create a new app.get with created name? 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), i.e. they're static, once the app has started, they can't be added dynamically.
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
In your case, try creating a route that will handle room names, and pass it room name as a URL parameter:
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);
});