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")
})
Related
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);
});
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);
});
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.
Novice to NodeJS and Express but lets say I have this route for mywebsite.com/tournaments.
router.get('/tournaments', function (req, res) {
TournamentController.getAllTournaments(function (err, docs) {
if (err) {
//render error
} else {
res.render('tournaments', {
data: {
title: 'mysite',
command: 'tournaments',
user: req.session.user,
tournaments: docs
}
});
}
});
});
data.tournaments is an array of tournaments in order of their date. Lets say in the front end I have a select/option form where the user can choose date/prize/players as the order to sort the tournaments by. How can I sort the data.tournaments without having to call another route or refresh the page? I'm using Jade on the front end.
You can always sort them directly in the Browser via Javascript, either do it yourself or use a plugin like datatables.
If you don't wanna do that but do it on the server, you'll need an ajax call for that and a route that handles the sorting (based on the parameters you pass), and afterwards change the DOM according to the response. This goes without refreshing the page, but you'll need a route for that, or change the existing route and extend your controller to take optional parameters, something like
router.get('/tournaments/:sort?', function (req, res) {
TournamentController.getAllTournaments(req.param('sort'), function (err, docs) {
/* ... */
});
});
I'm building a site that has somewhat reddit-like functionality. I want user-submitted content to get its own page. Each submission is assigned a 5 character ID that I want to be in the URL for that page.
I've got this function in the router file which renders a page called titles:
exports.titles = function(req, res){
i = 0
read(function(post){
url = post[i].URL;
res.render('titles', {title: post[i].title, url: post[i].URL});
});
};
It is served by this statement in app.js:
app.get('/titles', home.titles); //home.js is the router file
The titles page has a link with the text post.title and the URL post.URL. When a user clicks on the link (e.g. domain.com/12345) they should be taken to a page called content with the content post.body.
How do I a)pass the URL back to my app.js file to include in an app.get, b) include the app.get function in this router file, or c) solve this in any other way?
Edit: I do have an object 'titles' that is a mongodb collection, but it is in a different module. No reason I can't add it to the router though.
Edit: I tried adding this to app.js to see if it would work:
app.get('/:id', function(req, res){
return titles.findOne({ id: req.params.id }, function (err, post) {
if (err) throw(err);
return res.render('content', {title: post.title, content: post.body});
});
});
Edit: I got it to work. All I did was format the title so that it would look like domain.com/titles/12345 and change app.get('/:id', to app.get('/titles/:id, ...
If I get you right I would do that the other way around.
Short version
I would get the id from the URL
Then I would pull from the database the data associated with this id
And use this data to build the final page.
You don't need to create a new route for each URL. An URL can contain some variable (here the id) and Express can parse the URL in order to get this variable. Then from this id you can get the data needed to build the proper page.
Long version
I assuming someone type in this URL: http://domain.com/1234.
I also assume that you have a variable titles which is a MongoDB Collection.
You can have a route defined like this:
app.get('/:id', function(req, res) {
// Then you can use the value of the id with req.params.id
// So you use it to get the data from your database:
return titles.findOne({ id: req.params.id }, function (err, post) {
if (err) { throw(err); }
return res.render('titles', {title: post.title, url: post.URL /*, other data you need... */});
});
});
Edit
I made some changes according to the last comments...