【问题标题】:How to redirect to another page when click on hyperlink href using node js?使用节点js单击超链接href时如何重定向到另一个页面?
【发布时间】:2019-08-04 02:43:49
【问题描述】:

server.js:

var http = require('http');
var fs = require('fs');

function onRequest(request,response){
    response.writeHead(200, {'content-Type':'text/html'});
    fs.readFile('./index.html',null,function(error,data){
        if(error) 
        {
            response.writeHead(404);
            response.write('File not found');
        }
        else
        {
            response.write(data);
        }
        response.end();
    });
    fs.readFile('./about.html',null,function(error,data){
        if(error) 
        {
            response.writeHead(404);
            response.write('File not found');
        }
        else
        {
            response.write(data);
        }
        response.end();
    });
}

http.createServer(onRequest).listen(8080);

我是 Node.js 的新手,我在其中创建了一个简单的 HTML 页面,即文件夹内的 index.htmlabout.html。我还创建了一个server.js

现在,当我在 cmd 上运行命令并在 localhost:8080 上运行时,会显示 index.html 页面,但是当我单击超链接(即 <a href="about.html"></a>)时,它无法正常工作。

那么,如何在 node js 中创建超链接?

【问题讨论】:

标签: javascript html node.js


【解决方案1】:

要呈现不同的 html 文件,您必须使用基于 url 的重定向。我用你的例子来说明清楚。

index.html

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<a href="./about.html">go to about</a>
</body>
</html>

about.html

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
<a href="./index.html"> go to index</a>
</body>
</html>

server.js

var http = require('http');
var fs = require('fs');

function onRequest(request,response){
    response.writeHead(200, {'content-Type':'text/html'});
    if(request.url=='/' || request.url=='/index.html'){
        fs.readFile('./index.html',null,function(error,data){
            if(error) 
            {
                response.writeHead(404);
                response.write('File not found');
            }
            else
            {
                response.write(data);
            }
            response.end();
        });
    }
    if(request.url=='/about.html'){
        fs.readFile('./about.html',null,function(error,data){
            if(error) 
            {
                response.writeHead(404);
                response.write('File not found');
            }
            else
            {
                response.write(data);
            }
            response.end();
        });
    }
}

http.createServer(onRequest).listen(8080);

【讨论】:

    【解决方案2】:

    要在 express 中提供静态文件,您需要使用 express.static 配置中间件,如下所示:

    app.use('/', express.static('html'));
    

    这样,如果您的所有 html 文件都在 html 文件夹中,express 会将 / 映射到您的 html 文件所在的位置。

    请记住,路径“/”是相对于您启动节点进程的位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多