我在 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/