簡體   English   中英

使用node js單擊超鏈接href時如何重定向到另一個頁面?

[英]How to redirect to another page when click on hyperlink href using node js?

服務器.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>它不起作用。

那么,如何在節點 js 中創建超鏈接?

要呈現不同的 html 文件,您必須使用基於 url 的重定向。 我已經用你的例子使它更清楚。

索引.html

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

關於.html

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

服務器.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);

要在 express 中提供靜態文件,您需要使用 express.static 配置中間件,如下所示:

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

這樣,如果您將所有 html 文件都放在 html 文件夾中,express 會將 / 映射到您的 html 文件所在的位置。

請記住,路徑“/”與您啟動節點進程的位置相對。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM