2017-11-25 54 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

相關問題