簡體   English   中英

如何使用 Node.js web 服務器的超鏈接?

[英]How do you use hyperlinks with a Node.js web server?

我正在嘗試向用戶發送不同的 html 文件,其中 index.html 是一堆超鏈接,用戶可以單擊以查看該文件,但是每當我收到一條錯誤消息“無法獲取(該文件的名稱)”單擊一個超鏈接。

var app = require('express')();
var http = require('http').createServer(app);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});


http.listen(3000, function(){
  console.log('listening on *:3000');
});

這是我的索引。html:

<html>

<a href="/pongClient.html">Pong Game </a>

</html>

您可以像這樣定義一個公共 static 文件夾:

app.use(express.static(__dirname + '/public'));

您的公共文件夾中的所有內容都可以在 URL 的根目錄中訪問(即/pongClient.html

基本上,您必須設置node服務器,以便它知道從哪里獲取文件,並且在這種情況下,您可以設置 static 服務器。 express 中的語法可以在這里找到

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.

var app = require('express')();
var http = require('http').createServer(app);

app.use(express.static(__dirname)) //since the index.html and probably pongClient.html are in the current directory based on your code.

http.listen(3000, function(){
  console.log('listening on *:3000');
});

Nodejs 與超鏈接無關。 但是,如果您希望您的用戶訪問不同的頁面,請使用

app.get('/', function(req, res){
  res.send('<p><a href="http://localhost:80/pongClient.html">Pong Game</a></p>\n');
});

端口號是 80(我假設您的 web 服務器端口是 80)。主要是您必須提供完整的 URL(可訪問的)。

暫無
暫無

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

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