来自节点js的HTML代码不能被浏览器解释

我创build了我的第一个节点js应用程序:一个简单的networking服务器。 代码如下:

// Load the http module to create an http server. var http = require('http'); // Configure our HTTP server to respond with Hello World to all requests. var server = http.createServer(function (request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.end("<a href=\"http://www.tagesschau.de/\">ARD Tagesschau</a>\n"); }); // Listen on port 8000, IP defaults to 127.0.0.1 server.listen(8000); // Put a friendly message on the terminal console.log("Server running at http://127.0.0.1:8000/"); 

当我通过浏览器连接到服务器时,我得到了我的代码中指定的完整string作为网页。

浏览器不应该解释那个HTML代码并显示一个链接吗? 为什么我会以纯文本格式显示完整的HTML代码?

您明确表示您正在返回纯文本,而不是HTML。 浏览器因此将其视为纯文本。

如果你想HTML被视为HTML然后说它 HTML:

 {"Content-Type": "text/html"} 

(虽然你应该发回一个HTML文件,而不是HTML的片段)。

以下代码适用于我:

 var http = require('http'); // Configure our HTTP server to respond with Hello World to all requests. var server = http.createServer(function (request, response) { response.writeHead(200, {"Content-Type": "text/html"}); response.end("<a href=\"http://www.tagesschau.de/\">ARD Tagesschau</a>\n"); }); // Listen on port 8000, IP defaults to 127.0.0.1 server.listen(8000); // Put a friendly message on the terminal console.log("Server running at http://127.0.0.1:8000/"); 

您需要设置标题。 有关更多信息,请点击此处的Node API文档。

检查你的萤火虫或开发工具的差异,以了解浏览器根据标头内容types的不同解释。