最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何使用NodeJS重定向到另一个页面

网站源码admin21浏览0评论

如何使用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

发布评论

评论列表(0)

  1. 暂无评论