Update global variables on website after post - javascript

In index.js I am rendering page with global variables.
router.get('/index', function(req, res, next) {
res.render('index', { title: 'RLH',
countNumber: countNumber,
countReleased: countReleased,
countOpen: countOpen
});
in the same index.js I also have:
router.post('/index', function(req, res, next) {
datatamper = req.body;
countSev();
countTickets();
countTime();
});
On port 3000 I am listening for data, once I get it I am making some calculation and then the page is ready to be opened with global variables.
Clearly this is working just fine to open the page and all data will be here
On the page I am presenting data like that:
<p> <b> Tickets</b>: <span>{{countNumber}}</span></p>
Yet I would like to update just the data on the website by itself after every post(not refreshing the whole page).
Data by post is coming every minute, yet that might change.

You need to implement either some form of longpolling, where your javascript frontend sends requests to the api every so often to check for updates, and then adds them to the page, or use a technology like websockets to get the data as it's updated.

Related

How to use values between various Express routes

I am new to Express and writing an application in node js. I am having problem in using the same parameters. My code is:
app.get('/signin', function (req, res) {
renderView(req, res, 'signin.jade');
});
app.get('/config', function (req, res) {
addOrUpdateGroupConfig(req.query.group_name, req.query.webhook_url);
renderView(req, res, 'config.jade');
});
app.post('/config', function (req, res) {
..
}
function renderView(req, res, view, locals) {
if (locals === undefined) {
locals = {};
}
res.render(view, locals);
}
The sign in jade redirects to app.get(/config) and i am getting webhook_url and group_name. Now I am rendering a config jade page which has form post, after submit the control comes to app.post(/config) now the problem is i want the webhook_url and group_name here to store in database. SO how to pass those values in a good way ?
If the webhook_url and group_name values can't be put into the web page for security reasons, then the usual solution would be to create a session object and store it for that specific user in their session. Then, on the POST, you could get it out of that user's session. The express-session module is available to help you create a session object for each user. This is breaking with the usual stateless design of web pages so there'd have to be a really good reason to go this way.
Otherwise, the value should probably just be inserted into the form in a hidden field (by your renderer) so that when the POST happens, the value will be sent back with the form and you'll have everything you need in the POST data. That keeps your system entirely stateless which is good for a lot of reasons (simplicity, scalability, reliability, etc...).

Nodejs cannot Read and Write simultaneously

I am currently trying to develop a NodeJS application, which contains 3 main Routes:
app.get('/1',(req, res) => {
res.sendFile(path.join(__dirname, './index.html'))
});
app.post('/1',(req, res) => {
model.sharetime(req.body.zeit);
});
and
app.get('/receive', (req, res) => {
res.json(model.receivetime());
});
The post Route /1 will be called once ever second, which receives a value that is put into an array.
The problem that I encounter is, each time I want to call the route /receive while the /1 get route is open, there is no response whatsoever,
after I restart the server, suddenly I get the response that I requested.
Which basically means, I cant have the route /1 which opens my index file open which I need for the application to post results back to the server and simultaneously receive the updated values via the route /receive.
Please help :)
You're not responding to the request, you're merely calling a function with a value from the posted form. Add at least a res.end(); to that route handler.

Rerun routes with new URL

I have a small web server which serves as an optimizer for old URLs, it matches old urls and redirects to new nicer SEO-optimized urls.
One of the url is something like:
login.php?return=http://example.com/index.php?page=protected_page
Now after optimizing the service, http://example.com/index.php?page=protected_page is now just /page/protected_page/ and has the authentication inside, so naturally i put a match like
'login.php': function(req, res, next) {
if (req.query.return) {
res.redirect(req.query.return);
}
}
'index.php': function(req, res, next) {
if (req.query.page === 'protected_page') {
// redirect to proper seo page without index.php
res.redirect(...);
}
}
What will happen in this case, is that first the browser will get redirected to the url in req.query.return, then express will respond to the new request with a match on index.php. This is ok, but if the infrastructure is complicated, it will take some time for client browser to issue a new request (might even be 0.5-1 seconds if the person accessing the website is technically far from the server).
Any way I could take the req.query.return and have something like app.processNewUrl(req.query.return)?

Node.js Express: Redirect or render on post

I have a post route that looks something like this:
router.post('/:name/book', function(req, res){
Booking.create(myNewBooking, function(err, booking){
if(err){ return next(err); }
//What am I supposed to do here? I usually do:
req.app.locals.booking = booking;
res.render('booking_success.jade');
});
});
The problem: If the user refresh after doing this post request, they send the same data again. I don't want that to be possible. What is the best way to prevent this? I thought of this:
router.post('/:name/book', function(req, res){
Booking.create(myNewBooking, function(err, booking){
if(err){ return next(err); }
res.redirect('/booking-success');
});
});
router.get('/booking-success', function(req, res){
res.render('booking_success.jade');
});
Is this the way to go? Or are there better ways to do this?
Both of these options are done regularly. The reason to choose the redirect over the render is purely based on what you want to happen after the post.
If this is an API called by some external script (either Javascript via Ajax or any outside agent), then you should just render an acceptable (and probably small) response, often a simple piece of JSON.
If this is a form submission from a browser web page and you want the URL in the browser to end up on something that matches the rendered content, then a redirect makes great sense.
If this is a form submission, either option will clear the form from the browser and prevent a simple repost of the same data.
Though you can use both of the methods but looking at the above case you don't need to do res.redirect() and then res.render() you can directly do res.render() from the first route itself.
res.redirect() will be useful if you have routes which you can hit directly or via a redirect so that you don't have implement the same logic again in two places.

How to create a global function which will access DB in express.js

I use express.js, mongodb, ejs. In the navbar, there's an email icon and will display the count of new emails.
<%=newEmailCount%>
Then I need to add this newEmailCount to every route.
Emails.count({userId: userId, new: true})
my question is in express.js, how can I add a global function that can be executed by every route?
If you want to get the count for every GET requests then you can use following approach
router.get('*', function(req, res, next) {
res.locals.newEmailCount = Emails.count({userId: userId, new: true})
next();
})
You need to make sure this is always executed by placing it above all the other routes.
You can then pass res.locals.newEmailCount to your render function which renders HTML file for matched route.
This will work also for application instance level routes handling if that's what you're using.

Categories

Resources