1、html页面代码:
<!DOCTYPE html>
<html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } ul li{ float: left; width:200px; height: 50px; text-align: center; list-style: none; border: 0.1px solid #000; line-height: 50px; color:#fff; } .red{ background: red; } .blue{ background: blue; } .green{ background: green; } </style> </head> <body> <ul> <li class="red">1</li> <li class="blue">2</li> <li class="green">3</li> </ul> <img src="./showimg"/> </body></html>2.nodejs代码:
**********************创建服务器*******************
var http=require("http");
var url=require("url");var router=require("./02.js")http.createServer(function(req,res){ if(req.url!="/favicon.ico"){ pathname=url.parse(req.url).pathname; pathname=pathname.replace(/\//,""); console.log(pathname); try{ router[pathname](req,res); }catch(e){ console.log("11") console.log(e) } }}).listen(8000);console.log("server running at http://127.0.0.1:8000/")****************************路由******************************
var optfile=require("./03.js")
module.exports={ login:function(req,res){ res.writeHead(200,{"Content-Type":"text/html",charset:'utf-8'}); function recall(data){ res.write(data); res.end(""); } optfile.readfile("index.html",recall); }, showimg:function(req,res){ res.writeHead(200,{"Content-Type":"image/jpeg"}); optfile.readImg("./img/w.jpg",res); }}*****************************读取文档及图片*******************************
var fs=require("fs");
module.exports={ readfile:function(path,recall){ fs.readFile(path,function(err,data){ if(err){ recall("没有找到页面!"); }else{ console.log(data.toString()); recall(data); } }) }, readImg:function(path,res){ fs.readFile(path,"binary",function(err,file){ if(err){ console.log(err); }else{ res.write(file,"binary"); res.end(""); } }) }}