1

我创建了我的第一个节点 js 应用程序:一个简单的网络服务器。这是代码:

// 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/");

当我通过浏览器连接到服务器时,我将代码中指定的完整字符串作为网页获取。

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

4

2 回答 2

4

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

如果您希望将 HTML 视为 HTML,则说它HTML:

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

(尽管您应该发回 HTML 文档而不是 HTML 片段)。

于 2013-09-19T06:17:35.013 回答
2

以下代码对我有用:

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 文档。

检查您的 firebug 或开发工具中的差异,以了解浏览器如何根据 Header Content-Type进行不同的解释。

于 2013-09-19T06:21:40.130 回答