您可以使用 res.render() 或 res.redirect() 方法使用 node.js express 重定向到另一个页面
例如:
var bodyParser = require('body-parser');
var express = require('express');
var navigator = require('web-midi-api');
var app = express();
app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.get('/', function(req, res){
res.render("index");
});
//This reponds a post request for the login page
app.post('/login', function (req, res) {
console.log("Got a POST request for the login");
var data = {
"email": req.body.email,
"password": req.body.password
};
console.log(data);
//Data insertion code
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("college");
var query = { email: data.email };
dbo.collection("user").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
if(result[0].password == data.password)
res.redirect('dashboard.html');
else
res.redirect('login-error.html');
db.close();
});
});
});
// This responds a POST request for the add user
app.post('/insert', function (req, res) {
console.log("Got a POST request for the add user");
var data = {
"first_name" : req.body.firstName,
"second_name" : req.body.secondName,
"organization" : req.body.organization,
"email": req.body.email,
"mobile" : req.body.mobile,
};
console.log(data);
**res.render('success.html',{email:data.email,password:data.password});**
});
//make sure that Service Workers are supported.
if (navigator.serviceWorker) {
navigator.serviceWorker.register('service-worker.js', {scope: '/'})
.then(function (registration) {
console.log(registration);
})
.catch(function (e) {
console.error(e);
})
} else {
console.log('Service Worker is not supported in this browser.');
}
// TODO add service worker code here
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('service-worker.js')
.then(function() { console.log('Service Worker Registered'); });
}
var server = app.listen(63342, function () {
var host = server.address().host;
var port = server.address().port;
console.log("Example app listening at http://localhost:%s", port)
});
在登录部分,如果数据库中的电子邮件和密码匹配,则该站点将被定向到 dashbaord.html 否则我们将使用 res.redirect() 方法显示 page-error.html。您也可以使用 res.render() 在 node.js 中呈现页面