2017-11-25 96 views
1

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

我的代码是在Visual Studio代码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> 

回答

1

更改Content-Type头部为text/html:

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

哈哈,那工作谢谢! –

1

因为您将Content-type标头设置为text/plain眉头ser将在不解释HTML的情况下将内容显示为文本。

更改内容类型为text/html应该做的伎俩。

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

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

哈哈,那作品谢谢! –

+0

哈哈,太好了。请upvote和/或接受其中一个答案。 – mhawke

相关问题