Regarding routing in nodejs application - javascript

I had like 100 blogs on "/" page and also a link to Sortby Date:a-z When I click
these link I m transferred to different routes one is "/sort_by_date" and other is "/sort_alphabetically".I want this sorting to appear on "/".I m not able to do it on "/" page that is whay I had specified to different routes.I want this sorting to appear on "/" page by clicking to differnt links different sorting should be appear.This whole application is written in nodejs Mongoose express.
The homepage of the blog
router.get('/', function (req, res) {
var q= blog.find({}).limit(100);
q.exec(function(err,docs)
{
res.render('blog',{"no_of_blogs":docs
,"in_ca":true })
});
});
The page which is sorting by date
router.get('/sort_by_date', function (req, res) {
blog.find({},{sort:{date:-1}},function (err, docs) {
res.render('index_date_blog',{"no_of_blogs":docs
,"in_ca":true })
});
});
This is the page sorted by alphabetically
router.get('/sort_alphabetically', function (req, res) {
blog.find({},{sort:{title}},function (err, docs) {
res.render('index_date_blog',{"no_of_blogs":docs
,"in_ca":true })
});
});
Thanks in advance.

Use the query string to pass in the sort variable.
Make your links to change the sort link to ?sort=title or ?sort=date
Note, below code is not tested, but should help you along the way:
router.get('/', function (req, res) {
var sortQuery = req.query.sort;
var sort = {};
if(sortQuery=='date')
sort={date:-1}
if(sortQuery=='title')
sort={title: 1}
var q= blog.find({}).limit(100).sort(sort);
q.exec(function(err,docs)
{
res.render('blog',{"no_of_blogs":docs ,"in_ca":true })
});
});

Related

How do I set up an express route where parameters have multiple slashes?

I'm trying to set up an endpoint like below:
http://localhost:5000/guardian/lifeandstyle/2020/apr/26/bring-your-skin-to-life-with-a-hint-of-bronzer
I currently set up my endpoint like this:
router.get('/guardian/:articleId', (req, res) => {
const id = req.params.articleId;
console.log(id);
axios.get('https://content.guardianapis.com/'+ id +'?api-key=' + guardianapi + '&show-blocks=all')
.then(function (response) {
res.send(response.data);
});
});
But I'm getting a 404 error once I enter the endpoint in my browser
See the guide which has an example:
app.get('/users/:userId/books/:bookId', function (req, res) {
res.send(req.params)
})
You just put multiple / in the route and multiple names starting with a :.

express + pug app, update multiple routes when txt file changes?

I have a simple express + app that consists of two views. localhost:xxxx/ and localhost:xxxx/view view simply displays a number read from a text file, the index route allows the user to increment that number, and also displays it. These two views will be displayed in different browser tabs, and I am using Pug templates. I have the index view updating fine, but cannot figure out how to update both views when the value in the text file changes.
Main router file
router.get('/', function(req, res) {
let data = fs.readFileSync('./data.txt', 'utf8');
let number = parseInt(data);
res.render('index', { number });
})
router.post('/', countController.increment);
router.get('/view', countController.readFile);
Controller
exports.increment = (req, res) => {
let data = fs.readFileSync('./data.txt', 'utf8');
let number = parseInt(data);
number++;
fs.writeFile('./data.txt', number, function() {
res.render('index', { number });
});
}
exports.readFile = (req, res) => {
let number = fs.readFileSync('./data.txt', 'utf8');
res.render('view', { number })
}
Is there a way to update both views that are running in separate browsers, or do i need to use something like socket.io? Thanks!
Thanks for the tip on websockets! This post led me in the direction to solve it, passing in socketio to my router. Use socket.io inside a express routes file

Cannot GET / error in nodeJS

I am developing a simple MEAN stack application. I am using angular routing to redirect to a page based on the Id of the item clicked like this:
when('/story/:id', {
template: '<news-detail></news-detail>'
})
When an item is clicked it should go to a page like this : http://localhost:3002/story/58fbcf765865db1d8da94b41
but on that page I get a "Cannot GET /story/58fbcf765865db1d8da94b41" node error.
from back end I have tried this:
app.get('/story/:id', function(req, res){
if(req){
var id = req.params.id;
PostProfile.News.findById(id, function(err, item){
if(item){
console.log("found")
res.send(item)
}
})
}
})
This solution just displays some raw json on the page
{"_id":"58fbc2834f675c1cdb7dc628","title": .....
What is the walk around for this and how can I use angular to make the request by id without going through nodejs first.
thanks alot.
to go to some page you have to do res.render
Eg:
router.get('/story/:id', function(req, res) {
var id = req.params.id;
PostProfile.News.findById(id, function(err, item){
res.render('somePage', {
pageTitle: item.title,
body: item.body
});
})
});

Node JS Routing URL Conflict

Each piece of this code works individually but when put together, the Article section (third set) will not load. I am fairly new to coding so I was hoping for someone to point me in the right direction. I assume this is because the first route is executed and it never hits the second route...but I don't know how to fix it.
// Adds "www." to all URLs
app.all('*', function(req, res, next) {
if (req.headers.host.match(/^www/) == null) {
res.redirect('http://www.' + req.headers.host + req.url);
} else {
next();
}
});
// Serves the .html file but displays without .html in the URL
app.get('*', function(req,res){
var pages = ['/now', '/home', '/itinerary','/exploreourroots','/contact','/credits'];
if (pages.indexOf(req.url.toLowerCase()) !== -1) {
res.sendFile(__dirname + '/public' + req.url + '.html');
};
});
// Loads Articles from the database on the home page
app.get('/home', function(req, res) {
var query = 'SELECT a.title,a.author,a.cover_photo,a.html_loc,a.date_published,c.name country_name FROM articles a INNER JOIN countries c ON c.id=a.country_id ORDER BY a.date_published desc;'
connection.query(query, function(err, rows, fields) {
var list = [];
for (var i = 0;i < rows.length; i++) {
list.push({html_loc: rows[i].html_loc,country_name: rows[i].country_name,cover_photo: rows[i].cover_photo,title: rows[i].title,author: toAuthorPhoto(rows[i].author),date_published: toArticleDate(rows[i].date_published)});
}
res.contentType('application/json');
res.send(list);
});
});
Thanks for the help!
I'm not sure what intentions you have.
What if user type in browser www.mydomain.com/home. You want to return static html file (home.html), which is done by second router. Or you want to serve then article from db (third route)?
If you want to serve article from db when url is /home, then replace order of second and third routes:
app.get('/home', function(req, res) { ... });
app.get('*', function(req,res){ ... });
if you want to serve static html when your route is /home and also you want to have possibility to serve articles, then as before replace orders and additionally change /home router to /article. Then you will serve articles if url is /article :
app.get('/article', function(req, res) { ... });
app.get('*', function(req,res){ ... });

How target routes with 'lang?' in a middleware

I have this middleware:
app
.use('/:lang?', middleware.setLanguage)
.use('/thanks/:lang?', middleware.setLanguage)
.use('/forum/:lang?', middleware.setLanguage);
I want use a function called setLanguage in every route that have lang?, and currently this code is working, but i can believe dry that.
Someone knows how to? I search in the documentation, but didn't find anything..
Use .param to process the parameters up front so that you don't have to do it on every route that uses it. For example, here's one that starts building a query with moongoose for a product crud:
app.param('product_id', function (req, res, next, product_id) {
req.product_id = new ObjectId(product_id);
req.product = Product.findOne(req.product_id);
next();
});
// update product
app.put('/products/:product_id', function (req, res) {
Product.findOneAndUpdate(req.product_id, req.body, function (err, product) {
res.json(product.toObject());
});
});
// get product by id
app.get('/products/:product_id', function (req, res) {
req.product.lean().exec(function (err, product) {
res.json(product);
});
});
None of my routes have to get the product id and convert it to an ObjectId because i did that up front for all routes with .param.

Categories

Resources