node.js - 为什么我的 Node.js 服务器返回 html 代码而不是 html 网页

标签 node.js

我在 Node.js 上构建了一个简单的服务器。当我尝试通过服务器加载一个简单的 HTML 页面(由 Google Chrome 成功打开)时,localhost8888 显示 HTML 代码而不是页面。

我的代码在 Visual Studio Code IDE 上如下:

var http = require('http');
var fs = require('fs');

function send404response(response){
    response.writeHead(404,{'Content-Type': 'text/plain'});
    response.write('error 404: page not found');
    response.end();
}

function onRequest(request,response) {
    if(request.method == 'GET' && request.url == '/'){
        response.writeHead(200,{'Content-Type': 'text/plain'});
        fs.createReadStream('./index.html').pipe(response);
    }else{
        send404response(response);
    }

}

http.createServer(onRequest).listen(8888);
console.log("server is running ......")

我的index.html页面代码:

<!DOCTYPE html>
<html>
    <head lang = 'en'>
        <meta charset="UTF-8">
        <title> thenewboston </title>
    </head>
    <body>
        wow this site is awesome 
    </body>
</html>

最佳答案

因为你设置了Content-type将 header 添加到 text/plain 浏览器会将内容显示为文本,而不解释 HTML。

将内容类型更改为 text/html 应该可以解决问题。

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

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

关于node.js - 为什么我的 Node.js 服务器返回 html 代码而不是 html 网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47491221/

相关文章:

javascript - 在 Node.js 中读取 XML 文件

node.js - 如何将 Google API 的 AWS Lambda 函数列入白名单

mysql - Sequelize Eager Loading 两个相同的 N :M models one returns data other does not

node.js - Node Js中如何选择首先调用哪个函数

node.js - 更改为 ES6 导入与要求时的 CORS 问题

javascript - 类型错误 : Cannot read property &#39;location&#39; of undefined

javascript - NodeJS读取并生成SAS文件: xport and sas7bdat

javascript - Node.js - Nginx 502

javascript - 如何使用 webpack 保持我的 shebang 到位?

javascript - Node.js - 读取 CSV 文件无法处理行号 > 500 的情况