问题
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>
回答1:
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.
回答2:
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'));
});
来源:https://stackoverflow.com/questions/36002477/reload-page-in-node-js-using-express-and-ejs