javascript - 来自 node js 的 HTML 代码未被浏览器解释为这样

标签 javascript html node.js webserver

我已经创建了我的第一个 Node 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 代码显示为纯文本?

最佳答案

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

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

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

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

关于javascript - 来自 node js 的 HTML 代码未被浏览器解释为这样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18887292/

相关文章:

JavaScript 缓存对象并进行压缩

javascript - 通过 onClick 更改多个视频 src

javascript - 如何进行hapijs反向路由?

javascript - 如何在每个新月安排 node-cron 作业?

c# - 在 Windows Azure worker 角色上从 LESS 生成 CSS

javascript - <select> 未使用语义 UI 进行更新

javascript - 如何预填充下拉列表

html - 如何在中心垂直对齐两个 div,并在底部保留一个 div?

javascript - "Warning: Failed propType: Required prop ' 字段 ' was not specified in ' ReduxForm(MyForm) '"

javascript - jQuery .remove() 不工作,而其他内置函数是