Reload page in Node.js using Express and EJS
Solution 1
There is a thing called HTTP Referer
: It is an HTTP header field that identifies the address of the page that linked to the resource being requested.
If you want to refresh a page, after the user sends a request that changes something, just redirect to the referer.
app.get('/someRequest', function(request, response) {
// some things changed here.
response.redirect(request.get('referer'));
});
Solution 2
To reload the html page:
<script>
location.reload(true/false);
</script>
Also, you want to restart the server whenever a change is made use nodemon instead of nodejs to run your server.
To install nodemon:
npm install -g nodemon
To run the server(app.js is the main server file)
nodemon apps.js
Nodemon looks for the changes and restarts the server whenever found.
Comments
-
Adam Johns about 4 years
I'm trying to reload the browser page when the underlying data model changes:
var request = require('request'); var express = require('express'); var app = express(); var bodyParser = require('body-parser'); app.set('view engine', 'ejs'); app.use(bodyParser.urlencoded({ extended: false })); var requests; app.get('/', function(req, res) { res.render('index', { requests: requests }); }); app.listen(3000);
...and later when requests data model changes:
request.get('localhost:3000/', function(error, response, body) { console.log(body); });
but my browser page doesn't refresh unless I manually tap the refresh button with my mouse. What am I missing?
EDIT: Here is my
index.ejs
code:<!DOCTYPE html> <html> <ul> <% requests.forEach(function(match) { %> <form action="/acceptRequest" method="post" enctype="application/x-www-form-urlencoded"> <input type="text" name="id" value="<%= match.id %>"> <input type="text" name="fighter1" value="<%= match.fighter1 %>"> vs. <input type="text" name="fighter2" value="<%= match.fighter2 %>"> on <input type="text" name="fightdate" value="<%= match.date %>"> in <input type="text" name="rounds" value=""> <input type="submit" value="Submit"> </form> <br> <% }); %> </ul> </html>
-
Adam Johns about 8 yearsbut I need to reload outside of the
app.get
so I don't have access toresponse
. -
Akshay Arora about 8 years@AdamJohns, do you want to reload the
localhost:3000/
? -
frontsideup over 5 yearsThis "location.reload(true/false);" is so bad, please don't do this.
-
oldboy over 5 years@Undefined i dont want a file system menu, so ive used
Menu.setApplicationMenu(null)
, but now i have no way of reloading the page for the main window? i triedglobalShortcut.register('Ctrl+R', ()=>{ window.location.reload() })
but this obvs doesnt work. is there something else i can do? -
Ipsita Rout over 5 years@AdamJohns : Any progress? How did you solve? My requirement is same as yours :(
-
apYan over 2 yearsThis does not work