简体   繁体   中英

Express send new HTML page without redirect

I currently have a login page with node.js + express + socket.io. Is there a way to send the client a new HTML page without them being redirected? (ie stay on www.dns.com vs www.dns.con/home). I tried res.sendFile however the client does not see to accept the new HTML file.

Current Code

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html'); //sets initial HTML page
});

io.on('connection', function (socket) {
    socket.on('login', function (username) {
        if (username === 'user')
        {
            console.log("Login Sucessful");
            app.get('/', function (req, res) { 
                res.sendFile(__dirname + '/main.html'); //doesn't change HTML page
            });
        }
    });
});

http.listen(80, function () {
    console.log('listening on port 80');
});

By running

app.get('/', function (req, res) { 
    res.sendFile(__dirname + '/main.html'); //doesn't change HTML page
});

inside that if, you are just adding another route for future requests which is not what you want to do. And not the right thing to do in many other cases.

You can send the content of the HTML file over the socket and then on the client side, handle that. Have a javascript function that replaces the entire page with the given HTML content.

Or more efficient way, just send the path of the file, and over the client side, load the file using an ajax call then replace the whole page content with the result of the ajax call.

io.on('connection', function (socket) {
    socket.on('login', function (username) {
        if (username === 'user')
        {
            console.log("Login Sucessful");
            socket.send('replace-page', 'main.html'); // send the file name
        }
    });
});

On the client side, have a function that is listening for replace-page event. Based on which technology you are using, you can load the content and replace the page in many ways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM