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

编程入门 行业动态 更新时间:2024-10-12 05:50:20

<a href=https://www.elefans.com/category/jswz/34/1771452.html style=如何使用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重定向到另一个页面

本文发布于:2024-05-07 06:49:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754929.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   重定向   页面   NodeJS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!