response.redirect() with parameters - node.js

I want to redirect to a page where the path is like /users/home/:id
response.redirect('/users/home')
The above code will redirect to /users/home but I want to redirect it to a page like '/users/home/1' dynamically with parameters. How shall I solve it?Do explain with some examples

You could use template literals to form the new url, for example:
app.get("/users/home/:id", (req, res) => {
res.redirect(`/users/alternate_home/${req.params.id}`);
});
app.get("/users/alternate_home/:id", (req, res) => {
res.json(users);
});

Related

express route parameters not being set

I am trying to get route parameters working with express, i have the following code trying to use the colon to define the parameters, if I do just the station id it works app.get('/:stationId/ but adding on the radius part just doesn't return anything. What am i doing wrong?
app.get('/:stationId/asset?radius=:radius', (req, res) => {
console.log(req.params.stationId)
console.log(req.params.radius)
})
I know I would be able to change the url to be app.get('/:stationId/:radius but i need it in the other format.
Parameters after the ? are handled differently:
app.get("/:stationId/asset", (req, res) => {
console.log(req.params.stationId);
console.log(req.query.radius);
});

why does my routing not working (/user/create)

This is how I set up the routing:
I'm trying to render create page when the user access the url domain.com/user/create
but when I try, it redirects to my original .get("/") instead (.get("/create"))
My routes:
[1]: https://i.stack.imgur.com/WrCn4.png
My view folder structure:
[2]: https://i.stack.imgur.com/W9ngF.png
My app.js
[3]: https://i.stack.imgur.com/cfXIr.png
Edited (With new finding and including codes instead of images)
I found out this was because I have the router with :email parameter.
router.get("/:email", userController.GetUserByParam, (req, res) => {
console.log(req.data);
res.render("user", { userList: req.data, date: req.date });
//res.send(req.data);
});
I just don't understand why that interfere with my create routing?
router.get("/create", (req, res) => {
//res.send("Test");
res.render("Create");
});
remove "/" before create and also add your controller after create.
if you want add data in database you need to use post
router.post("create",controller.something(req,res)=>{
res.render("created")
})

How to use two responses at once?

I have a working template engine (pug) to fill it's website with content depending from the situation. Acutally that template is rendered for the site '/show'.
Now I also need to change the url of this website depending from the content. That means I need the same template with new content for sites like: '/tree', '/house', '/urban' an do so. '/show' is the starting point, I need to change it's url with the new content.
I'm sure there is an easy answer, but I can't find the fitting question for that. So I can't find the right answer per searchengine. (Express.js res.render() and res.redirect() was my closest success, but it is not helpful for me.
I know, the following code is incorrect, at least because of the two resp.
server.get('/show', (req, resp) => {
loadContent(function(err, content){
if(content){
resp.location('/tree');
resp.render('myTemplate', content);
} else{
console.log(err);
}
})
});
How can I send my content to the template and replace the url to see both on the browser?
to send data to your pug template with express js use this syntax
const router = require('express').Router();
server.get('/show', (req, res, next) => {
loadContent(function(err, content){
if(content){
res.render('myTemplate', { content: content });
} else{
console.log(err);
}
})
and you will get it
script.
var content = !{content};
Well, I've found my problem. My approach was incorrect.
With
server.get('/:kindOfSite', function(req, resp){...});
I'm able to load the same template for different sites.
Learning can get hard sometimes...
Remember that your express route handlers are just functions. There's nothing that forces you to use an anonymous function. You can just use a regular function:
function handleRequest (req, resp) {
loadContent(function(err, content){
if(content){
resp.location('/tree');
resp.render('myTemplate', content);
} else{
console.log(err);
}
})
}
server.get('/show', handleRequest);
server.get('/tree', handleRequest);
server.get('/house', handleRequest);
server.get('/urban', handleRequest);
Indeed, you can do a bit of metaprogramming and call server.get() in a loop:
['/show','/tree','/house','/urban].forEach(route => {
server.get(route,handleRequest)
});
In fact, Express accepts regular expressions as route paths:
server.get(/\/(show|tree|house|urban)/, (req, resp) => {
loadContent(function(err, content){
if(content){
resp.location('/tree');
resp.render('myTemplate', content);
} else{
console.log(err);
}
})
});

res.send() after res.redirect() in nodejs

I am trying to send a variable to the page after I have redirected to another page. I have very basic knowledge in Node.js and can't seem to figure out a way to do that. Here's my code.
app.get('/search' , function (req, res) {
var postcode = req.query.search;
var ward = my_search.getWardNum(postcode,(ward) => {
res.redirect('/:ward'+ ward);
});
});
app.get('/ws/:postcode' , function (req, res) {
var postcode = req.params.postcode.replace("+","");
console.log(pc);
my_search.postcodeLookUp(pc,(ward) => {
var area = my_search.lookupWard(ward);
res.send(area);
});
});
So in the first app.get(), I get the postcode and redirect to another page.
However, I still need that postcode with second app.get().
I understand that nature of node.js is async. Is there a way to do what I want to do?
When you "redirect", you're not just changing the URL the user sees, you're sending a HTTP response with a status code indicating that the client should try to access another page instead.
You can't send data after you redirect because the full response has already been sent! You should consider why you're redirecting and if it is really necessary. You could also redirect to a route containing the URL parameter that you want to be present:
res.redirect('/ward/' + ward + '/' + postcode);
...
app.get('/ward/:wardID/:postcode', (req, res, next) => {
// route code here...
});
Note that you'll probably want a prettier format than that, but that is one way to accomplish this.

How to use multiple language routes with node and i18n?

I am building a simple website and would like the links to be translated.
Ex:
about-us / a-propos-de-nous
Currently, I've noticed that to set the language with i18n, you need to redirect the user in order for it to catch on by doing something like:
app.get('/fr', (req, res) => {
i18n.setLocale('fr');
res.cookie('i18n', 'fr');
res.redirect('/');
});
But how would that work if a user visit the following urls directly?
app.get(['/about-us', '/a-propos-de-nous'], (req, res) => {
// How do I set the proper locale here? I can't do any redirect otherwise
// I'll be caught in a redirect loop.
res.render('about-us');
});
You can get the requested path from req.url, you could check which one it was and set the language accordingly.
app.get(['/about-us', '/a-propos-de-nous'], (req, res) => {
if(req.url === '/about-us') {
i18n.setLocale('en');
res.cookie('i18n', 'en');
} else if(req.url === '/a-propos-de-nous') {
i18n.setLocale('fr');
res.cookie('i18n', 'fr');
}
res.render('about-us');
});
You could also prefix the path like example.com/fr/a-propos-de-nous, which would make it a little easier to extract the language from the request.

Resources