I am passing the title to the EJS pages from node js as below
router.get('/Home', function(req, res, next) {
res.render('Pages/Home', { title: 'Home' });
});
Can I pass a second parameter along with this as..?
router.get('/Home', function(req, res, next) {
res.render('Pages/Home', { title: 'Home' },{ role: 'Admin' });
});
Yes you can but you need to wrap all your needed parameters in one object like so:
router.get('/Home', function(req, res, next) {
res.render('Pages/Home', { title: 'Home', role: 'Admin' });
});
Related
My first time using Node.js/express routes, I cannot match when I use parameters
<a href="/produtos/1/produto-test">
app.use('/produtos', produtosRouter);
//below the produtosRouter, function
router.get('/', function(req, res, next) {
res.render('produtos/:id/:slug', { title: 'test test.' });
});
Does this help?
router.get('/:id/:slug', function(req, res, next){
res.render('<name_of_the_template>', { title: 'test test.'});
});
I am using express and I want to have my user profile URLs like this: example.com/:username
However, I still need other URLs such as example.com/login and example.com/view/:id
If I order the router like this, it treats "login" as a username when a request is sent to example.com/login:
router.get('/:username', function (req, res, next) {
res.render('profile', {data: req.params.username});
})
router.get('/login', function (req, res, next) {
res.render('login', {data: null});
})
router.get('/view/:id', function (req, res, next) {
res.render('view', {data: req.params.id});
})
If I put the /:username router at the end, everything works correctly. However, if someone went to example.com/view (without an id), I need it to send an error that the view controller didn't receive an id. Instead, it sees it as a username again and instead sends an error that the username doesn't exist.
What is the cleanest way to solve this? Do I just have to add a router for all base url paths? (Something like this):
router.get('/login', function (req, res, next) {
res.render('login', {data: null});
})
router.get('/view/:id', function (req, res, next) {
res.render('view', {data: req.params.id});
})
router.get('/view', function (req, res, next) {
res.render('viewError', {data: null});
})
router.get('/:username', function (req, res, next) {
res.render('profile', {data: req.params.username});
})
I am not entirely sure if this is the right way to do it, but then again this sounds like something I might encounter and I would like it to be solved by this method until I find a better solution.
The below solution uses a single route for the path format /:value, be it login, view or any username, hence you could put in a simple if-else-if or switch to give control to respective controllers or just simply render a view from it. This way the order in which it has to be handled doesn't matter at all.
router.get("/:username", function(req, res, next) {
if (req.params.username === "login") {
res.render("login", { data: null });
} else if (req.params.username === "view") {
res.render("viewError", { data: null });
} else {
res.render("profile", { data: req.params.username });
}
});
router.get("/view/:id", function(req, res, next) {
res.render("view", { data: req.params.id });
});
I am learning Express.js, MongoDB and Mongoose, and i am creating a small app that lets me store items to a list.
I am trying to Create a GET /list/search route which allows to search for items in the list, but i haven't gotten it to work.
Here is my code
Routes
const express = require('express');
router = express.Router();
const db = require("../models");
router.get('/', function(req, res, next){
db.List.find().then(function(list){
res.render('index', {list});
});
});
router.get('/new', function(req, res, next){
res.render('new');
});
router.get('/:id', function(req, res, next){
db.List.findById(req.params.id).then(function(list){
res.render('show', {list});
});
});
router.get('/:id/edit', function(req, res, next){
db.List.findById(req.params.id).then(function(list){
res.render('edit', {list});
});
});
router.get('/search', function(req, res, next){
db.List.findOne(req.query.search).then(function(list){
console.log(list);
res.render('show', {list});
});
});
router.post('/', function(req, res, next){
db.List.create(req.body).then(function(list){
res.redirect('/');
});
});
router.patch('/:id', function(req, res, next){
db.List.findByIdAndUpdate(req.params.id, req.body).then(function(list){
res.redirect('/');
});
});
router.delete('/:id', function(req, res, next){
db.List.findByIdAndRemove(req.params.id).then(function(list){
res.redirect('/');
});
});
module.exports = router;
Index.pug
extends base.pug
block content
h1 My List
form(action="/list/search" method="GET")
input(type="text" name="search")
input(type="submit", value="search")
a(href="/list/new") Add New Item!
each item in list
p ITEM: #{item.name} QUANTITY: #{item.quantity}
a(href=`/list/${item.id}/edit`) Edit
my main problem is the GET /search, i want to pass in a search query to the search box and return the result to the render file
router.get('/search', function(req, res, next){
db.List.findOne(req.query.search).then(function(list){
console.log(list);
res.render('show', {list});
});
});
Thanks in advance
You need to specify the parameters as attributes in the query. list will be null, if no matching record was found.
router.get('/search', function (req, res, next) {
db.List.findOne({
name: req.query.name,
age: req.query.age
}).then(function (list) {
console.log(list);
if (list === null) {
return res.render('show', {
list: []
});
}
return res.render('show', {
list: list
});
}).catch((err) => {
console.log('err', err);
return res.render('show', {
list: []
});
});
});
I am currently working on a project that uses MongoDB, Express, and Jade. We always want to throw the user account JSON data into the view. Every single controller we have, we are writing
exports.theView = function(req, res){
User.findOne({ username: req.user.username }, function(err, user){
res.render('theview.jade', { user: user });
});
}
There seems like there should be a better, more efficient way of doing this.
Any suggestions?
I think you can use middleware to set response locals (http://expressjs.com/api.html#res.locals) to set user to view every reqeust.
Middleware:
app.use(function(req, res, next) {
User.findOne({ username: req.user.username }, function(err, user){
res.locals.user = req.user;
next()
});
});
Route:
app.get('/', function(req, res, next) {
res.render('theview.jade', {title: 'Title'});
});
View:
block content
h1= title
p= user.name
in node.js, lets say for example i have 5 somename.js files in my route dir
and in each one i have 5 exports.some_page_url method
so like this i have 25 routes in my app
do i need in my app.js to write 25 routes?
for example
app.get('/', routes.index);
app.get('/p1', routes.page1);
app.get('/p2', routes.page2);
app.get('/p3', routes.page3);
app.get('/p4', routes.page4);
app.get('/p5', routes.page5);
app.get('/p6', routes.page6);
app.get('/p7', routes.page7);
app.get('/p8', routes.page8);
app.get('/p9', routes.page9);
...
index.js file
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
exports.page1 = function(req, res){
//some methods
res.render('page1', { title: 'Express' });
};
exports.page2 = function(req, res){
//some methods
res.render('page2', { title: 'Express' });
};
exports.page3 = function(req, res){
//some methods
res.render('page3', { title: 'Express' });
};
exports.page4 = function(req, res){
//some methods
res.render('page4', { title: 'Express' });
};
and of course each page has a different logic
You can simply use routing system within express:
app.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
app.get('/page/:id', function(req, res, next) {
res.render('page' + req.params.id, { title: 'Express' });
});