1.url的获取
var server = http.createServer(function(req,res){
pathname = url.parse(req.url).pathname;
console.log(pathname);
if(pathname == '/'){
res.write('jwr');
res.end();
}else{
res.write(pathname);
res.end();
}
});
server.listen(port,ip);
2.前端读取
var http = require('http');
var url = require('url');
var fs = require('fs');
//在这里一般端口3000以上
var port = 12342;
var ip = '192.168.1.105';
var server = new http.Server();// 调用http中server方法
server.listen(port,ip);//开始接听
server.on('request',(req,res) => {
//获取得到url地址
var pathname = url.parse(req.url).pathname;
switch(pathname){
case "" || "/":
// fs获取当前index.html的文件内容
fs.readFile("./index.html",(err, content) =>{
if(err){
res.writeHead(404,{'content-tyle':'text/plain;charset="utf-8"'});
res.write(err.message);
res.end();
}else{
res.writeHead(200,{'content-tyle':'text/html;charset="utf-8"'});
res.write(content);
res.end();
}
});
break;
default:
//查看url的格式
var filename = pathname.substring(1);
console.log(filename);
var type = ' ';
//调用自定义方法getType
getType(filename.substring(filename.lastIndexOf('.')+1));
fs.readFile(filename,(err, content) =>{
if(err){
res.writeHead(404,{'content-tyle':'text/plain;charset="utf-8"'});
res.write(err.message);
res.end();
}else{
res.writeHead(200,{'content-tyle':'text/html;charset="utf-8"'});
res.write(content);
res.end();
}
});
}
});
function getType(endtag){
var type = null;
switch(endtag){
case "css":
type = "text/css;charset='utf-8'"
break;
case "js":
type = "text/javascript;charset='utf-8'"
break;
case "htm":
type = "text/html;charset='utf-8'"
break;
default:
}
//一定以函数记得要返回值
return type;
}
网友评论