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