我在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>
哈哈,那工作謝謝! –