
完整代码
//1.引入http的模块
var http= require('http');
var fs=require('fs');//读取页面内容
var path=require('path');//拼接
const { throws } = require('assert');
//2.创建服务器
var server= http.createServer();
//3.启动服务器
server.listen(3000,function () {
console.log('server .... start.. success');
});
//4.监听客户发送过来的请求,并相应数据给客户端 request(请求对象) response(响应对象)
server.on('request',function (request,response) {
//获取的请求路径
var url= request.url;
//响应乱码处理
//response.setHeader("cont")
if(url==='/login'){
//读取文件 nodeDeme/static/login.html
fs.readFile(path.join(__dirname,'static/login.html'),'utf8',function (err,data) {
if(err){
throw err;
}
response.end(data);
});
}else if(url==='/register'){
fs.readFile(path.join(__dirname,'static/register.html'),'utf8',function (err,data) {
if(err){
throw err;
}
response.end(data);
});
}
else if(url==='/'){
fs.readFile(path.join(__dirname,'static/index.html'),'utf8',function (err,data) {
if(err){
throw err;
}
response.end(data);
});
}
else if(url==='/add'){
fs.readFile(path.join(__dirname,'static/add.html'),'utf8',function (err,data) {
if(err){
throw err;
}
response.end(data);
});
}else {
fs.readFile(path.join(__dirname,'static/404.html'),'utf8',function (err,data) {
if(err){
throw err;
}
response.end(data);
});
}
});
改进之后
//1.引入http模块 path模块(拼接路径) fs模块 文件读写
var http = require('http');
var fs = require('fs');
var path = require('path');
const { ifError } = require('assert');
//2.创建服务器
var serve = http.createServer();
//3.启动服务器
serve.listen(3000,function(){
console.log('server start success!')
});
//4.监听客户端发来的请求
serve.on('request',function(request,response){
//获取请求路径
var url = request.url;
//根据不同的请求,找对应的页面
var filepath;
if(url==='/'){
filepath = path.join(__dirname,'public/index.html');
//读取页面内容
fs.readFile(filepath,'utf8',function(err,data){
if(err){
throw err;
}else{
response.end(data);
}
})
}else{
if(url.indexOf('.')>=0){
filepath= path.join(__dirname,'public',url);
}else{
filepath= path.join(__dirname,'public',url+'.html');
}
//读取页面内容
fs.readFile(filepath,'utf8',function(err,data){
if(err){
throw err;
}else{
response.end(data);
}
})
}
})