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

我已经在Node.js上构build了一个简单的服务器。 当我尝试加载一个简单的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标题更改为text / html:

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

由于您将Content-type标题设置为text/plain因此浏览器将在不解释HTML的情况下将内容显示为文本。

将内容types更改为text/html应该可以做到。

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

要么

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