如何使用NodeJS重定向到另一个页面"/>
如何使用NodeJS重定向到另一个页面
我是NodeJS的新手。我希望页面可以通过单击首页重定向到另一页。有人可以帮我解决问题。任何帮助将不胜感激。这是代码
app.js
var express = require('express');
var app = express();
app.get('/', function(req,res){
res.status(200).sendFile(__dirname + '/index.html');
});
app.get('/newPage.html', (req, res) => res.redirect('/newPage.html'))
var server = app.listen(process.env.PORT || '3000', function(){
console.log('App listening on Port %s', server.address().port);
console.log('Press Ctrl+C to quit');
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>NodeJS - HTML/CSS</title>
</head>
<body>
<h1>NodeJS HTML and CSS Demo</h1>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Maiores saepe quae debitis alias illum, animi sunt iste
</p>
<a href= "newPage.html">new page</a>
</body>
</html>
newPage.html
<!DOCTYPE html>
<html>
<head>
<title>New page</title>
</head>
<body>
<h1>This is the new page</h1>
</body>
</html>
回答如下:您可以执行以下操作:
app.js
var express = require('express');
var app = express();
app.get('/', function(req,res){
res.status(200).sendFile(__dirname + '/index.html');
});
app.get('/newPage', function(req,res){
res.status(200).sendFile(__dirname + '/newPage.html');
});
var server = app.listen(process.env.PORT || '3000', function(){
console.log('App listening on Port %s', server.address().port);
console.log('Press Ctrl+C to quit');
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>NodeJS - HTML/CSS</title>
</head>
<body>
<h1>NodeJS HTML and CSS Demo</h1>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Maiores saepe quae debitis alias illum, animi sunt iste
</p>
<a href="/newPage">new page</a>
</body>
</html>
鉴于此,如果您只想拥有一个静态网站,建议您查看express static files或node-static
更多推荐
如何使用NodeJS重定向到另一个页面
发布评论