使用节点js单击超链接href时如何重定向到另一个页面?

时间:2019-03-13 12:11:09

标签: javascript html node.js

server.js:

MySpecialComponent

我是Node.js的新手,在其中创建了一个简单的HTML页面,即文件夹内的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); index.html。我还创建了一个about.html

现在,当我在server.js上运行命令并在cmd上运行时,将显示index.html页面,但是当我单击超链接(即localhost:8080)时,它将无法正常工作。

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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

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

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

请记住,路径“ /”是从您开始节点进程的位置开始的相对路径。