在node.js中使用res()时忽略标记

时间:2015-03-30 06:47:06

标签: javascript node.js

我找不到任何相关内容所以我想我会在这里发布。我是node.js的新手

我尝试使用节点js创建一个按钮,其代码如下:

response.writeHead(200, {"Content-Type": "text/plain"});
response.end('<!DOCTYPE html><html><head><body><button type="button">Click Me!</button></body></head></html>');

然而,当在浏览器上看到时,它会显示:

<!DOCTYPE html>
 <html>
  <head>
   <body>
    <button type="button">Click Me!</button>
   </body>
  </head>
 </html>

好像完全忽略了标签。

检查html源代码,它看起来像这样:

<html>
<head>
<style type="text/css"></style>
</head>
<body>
<pre style="word-wrap:break-word; white-space: pre-wrap;">
<!DOCTYPE html>
<html>
 <head>
  <body>
   <button type="button">Click Me!</button>
  </body>
 </head>
</html>
</pre>
</body>
</html>

任何想法为什么会这样?谢谢!

1 个答案:

答案 0 :(得分:1)

这种情况正在发生,因为您text/plainresponse.writeHead(200, {"Content-Type": "text/plain"});需要 text/html

response.writeHead(200, {"Content-Type": "text/html"});

使用text/plain将不会解析响应,您将获得所提供的内容,纯文本(或“标记被忽略”)。

使用text/html会告诉浏览器这是HTML,需要对其进行解析。