nodejs基础(一)创建服务器,分发路由,读文件,写文件,读取图片,图文一起显示

response.writeHead(statusCode,[reasonPhrase], [headers]);

发送一个响应头给请求。 状态码是一个三位数的 HTTP 状态码,如 404。 最后一个参数 headers 是响应头。 第二个参数 statusMessage 是可选的状态描述。

例子:

const body = 'hello world';
response.writeHead(200, {
  'Content-Length': Buffer.byteLength(body),
  'Content-Type': 'text/plain' });

 

res.writeHeader(200, {'Content-Type':'text/javascript;charset=UTF-8'})

该方法在消息中只能被调用一次,且必须在 response.end() 被调用之前调用。

如果在调用该方法之前调用 response.write() 或 response.end(),则隐式的响应头会被处理并调用该函数。

response.setHeader() 设置的响应头会与 response.writeHead() 设置的响应头合并,且 response.writeHead() 的优先。

复制代码
// 返回 content-type = text/plain
const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('X-Foo', 'bar');
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('ok');
});
复制代码

 

注意,Content-Length 是以字节(而不是字符)为单位的。 上面的例子行得通是因为字符串 'hello world' 只包含单字节字符。 如果响应主体包含高级编码的字符,则应使用 Buffer.byteLength()来确定在给定编码中的字节数。 Node.js 不会检查 Content-Length 与已发送的响应主体的长度是否相同。

如果响应头字段的名称或值包含无效字符,则抛出 TypeError 错误。

 response.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});----吧服务器返回的数据当做HTML网页解析;在这里设置utf-8比在HTML中设置优先级高;

  response.writeHead(200, {'Content-Type': 'text/plain'});----吧服务器返回的数据当做字符串解析;

 response.writeHead(200,'hhhh');------服务器返回的状态码,可以200,202,404.。。。。。

response.setHeader('Content-Type': 'text/html');----吧服务器返回的数据当做HTML网页解析;

====================

var pathname = url.parse(request.url).pathname;----------url是完整的域名加上路径,pathname是域名后边的路径;

var rdata=url.parse(req.url,true).query;--------query是get返回的对象,get请求的参数都在对象中;


****************创建服务器

=====创建服务器的文件(当有http请求时,就会调用下面的的http.createServer(function (request, response) {}方法,显示在前端的内容都是response.write()返回出去的)

var http = require('http');
var fs = require('fs');
var url = require('url');
var routes=require('./models/routes');//引入文件的路径
var optfile=require(./models/optFile);
http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
console.log("dddddd");
  var pathname = url.parse(request.url).pathname;
if(pathname!="/favicon.ico"){
   // 输出请求的文件名
   console.log("Request for " + pathname + " received.");
pathname=pathname.replace(/\//,"");
  routes[pathname](request,response);//根据路径分发路由,执行相应的程序
      //  发送响应数据
      response.end("sss");// 如果没有这句话,则网页一直在加载,不完成;
   }
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');


=====路由的文件

module.exports={
login:function(req,res){
  res.write("登陆方法");
},
regist:function(req,res){
  res.write("注册方法");
}
}


*****************************

创建服务器:

var http = require('http');
var fs = require('fs');
var url = require('url');
var routes=require('./models/routes');
var optfile=require("./models/optFile");
http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
   var pathname = url.parse(request.url).pathname;
if(pathname!="/favicon.ico"){
  //创建一个闭包,作为参数传过去
  function recall(data){
    response.write(data);//  发送响应数据,在网页上显示
    response.end("ok");// 如果没有这句话,则网页一直在加载,不完成;
  }
// optfile.readfileSync("D:nodejs/views/login.html");//同步读取文件
optfile.readfile("D:nodejs/views/login.html",recall);//异步读取文件
console.log("主程序执行完毕");
   }
}).listen(8000);

==================

路由文件:optFile.js

var fs=require('fs');//引入文件操作模块
module.exports={
readfileSync:function(path){
  var data=fs.readFileSync(path,'utf-8');//同步方法读取文件
  console.log(data);
  console.log('同步方法执行完毕');
},
readfile:function(path,recall){
  fs.readFile(path,function(err,data){
if(err){
  console.log(err);
}else {
  console.log(data.toString());
  recall(data);
}
  });
  console.log("异步方法执行完毕");
}
}

================被读取的文件:login.html


====================读文件

创建服务器:

var http = require('http');
var fs = require('fs');
var url = require('url');
var routes=require('./models/routes');
http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
   var pathname = url.parse(request.url).pathname;
if(pathname!="/favicon.ico"){
  pathname=pathname.replace(/\//,"");// 吧/去掉
    routes[pathname](request,response);//根据路径分发路由,执行相应的程序
console.log("主程序执行完毕");
   }
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');


=====================

分发路由:routes.js

=======================

var optfile=require("../models/optFile");
module.exports={
login:function(req,res){
  //创建一个闭包,作为参数传过去
  function recall(data){
    res.write(data);//  发送响应数据,在网页上显示
    res.end("ok");// 如果没有这句话,则网页一直在加载,不完成;就没有http协议尾部
  }
// optfile.readfileSync("D:nodejs/views/login.html");//同步读取文件
optfile.readfile("D:nodejs/views/login.html",recall);//异步读取文件
},
regist:function(req,res){
  //创建一个闭包,作为参数传过去
  function recall(data){
    res.write(data);//  发送响应数据,在网页上显示
    res.end("ok");// 如果没有这句话,则网页一直在加载,不完成;
  }
// optfile.readfileSync("D:nodejs/views/login.html");//同步读取文件
optfile.readfile("D:nodejs/views/regist.html",recall);//异步读取文件
}

显示的网页:regist.html

=================写文件

创建服务器:

var http = require('http');
var fs = require('fs');
var url = require('url');
var routes=require('./models/routes');
http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
   var pathname = url.parse(request.url).pathname;
if(pathname!="/favicon.ico"){
  pathname=pathname.replace(/\//,"");// 吧/去掉
    routes[pathname](request,response);//根据路径分发路由,执行相应的程序
console.log("主程序执行完毕");
   }
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');

var optfile=require("../models/optFile");

module.exports={
login:function(req,res){
  //创建一个闭包,作为参数传过去
  function recall(data){
    res.write(data);//  发送响应数据,在网页上显示
    res.end("ok");// 如果没有这句话,则网页一直在加载,不完成;就没有http协议尾部
  }
// optfile.readfileSync("D:nodejs/views/login.html");//同步读取文件
optfile.readfile("D:nodejs/views/login.html",recall);//异步读取文件
},
regist:function(req,res){
  //创建一个闭包,作为参数传过去
  function recall(data){
    res.write(data);//  发送响应数据,在网页上显示
    res.end("ok");// 如果没有这句话,则网页一直在加载,不完成;
  }
// optfile.readfileSync("D:nodejs/views/login.html");//同步读取文件
optfile.readfile("D:nodejs/views/regist.html",recall);//异步读取文件
},
//写文件
writeFile:function(req,res){
  function recall(data){
    res.write(data);//  发送响应数据,在网页上显示
    res.end("ok");// 如果没有这句话,则网页一直在加载,不完成;
  }
  optfile.writeFile("D:nodejs/views/write.text","写文件",recall);
}
}

var fs=require('fs');//引入文件操作模块
module.exports={
readfileSync:function(path){
  var data=fs.readFileSync(path,'utf-8');//同步方法读取文件
  console.log(data);
  console.log('同步方法执行完毕');
},
readfile:function(path,recall){
  fs.readFile(path,function(err,data){
if(err){
  console.log(err);
}else {
  console.log(data.toString());
  recall(data);
}
  });
  console.log("异步方法执行完毕");
},
//异步写文件
writeFile:function (path,data,recall){
  fs.writeFile(path,data,function(err){
if(err){
  throw err;
}
console.log("savesuccess");
recall("写文件成功");
  });
}
}

====================================读取图片

*********

var http = require('http');
var fs = require('fs');
var url = require('url');
var routes=require('./models/routes');
http.createServer(function (request, response) {
  // response.writeHead(200, {'Content-Type': 'text/plain'});
    response.writeHead(200, {'Content-Type': 'image/jpeg'});
   var pathname = url.parse(request.url).pathname;
if(pathname!="/favicon.ico"){
  pathname=pathname.replace(/\//,"");// 吧/去掉
    routes[pathname](request,response);//根据路径分发路由,执行相应的程序


console.log("主程序执行完毕");
   }
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');

*******路由

var optfile=require("../models/optFile");
module.exports={
login:function(req,res){
  //创建一个闭包,作为参数传过去
  function recall(data){
    res.write(data);//  发送响应数据,在网页上显示
    res.end("ok");// 如果没有这句话,则网页一直在加载,不完成;就没有http协议尾部
  }
// optfile.readfileSync("D:nodejs/views/login.html");//同步读取文件
optfile.readfile("D:nodejs/views/login.html",recall);//异步读取文件
},
regist:function(req,res){
  //创建一个闭包,作为参数传过去
  function recall(data){
    res.write(data);//  发送响应数据,在网页上显示
    res.end("ok");// 如果没有这句话,则网页一直在加载,不完成;
  }
// optfile.readfileSync("D:nodejs/views/login.html");//同步读取文件
optfile.readfile("D:nodejs/views/regist.html",recall);//异步读取文件
},
//写文件
writeFile:function(req,res){
  function recall(data){
    res.write(data);//  发送响应数据,在网页上显示
    res.end("ok");// 如果没有这句话,则网页一直在加载,不完成;
  }
  optfile.writeFile("D:nodejs/views/write.text","写文件",recall);
},
readImage:function(req,res){
  function recall(data){
    res.write(data,"binary");// 图片的二进制数据
    res.end("ok");// 如果没有这句话,则网页一直在加载,不完成;
  }
  optfile.readImage("D:nodejs/images/one.jpg",recall);
}
}*

var fs=require('fs');//引入文件操作模块
module.exports={
readfileSync:function(path){
  var data=fs.readFileSync(path,'utf-8');//同步方法读取文件
  console.log(data);
  console.log('同步方法执行完毕');
},
readfile:function(path,recall){
  fs.readFile(path,function(err,data){
if(err){
  console.log(err);
}else {
  console.log(data.toString());
  recall(data);
}
  });
  console.log("异步方法执行完毕");
},
//读取图片
readImage:function(path,recall){
  fs.readFile(path,"binary",function(err,data){
    if(err){
      console.log(err);
      return;
    }else {
      recall(data);
    }
  });
},
//异步写文件
writeFile:function (path,data,recall){
  fs.writeFile(path,data,function(err){
if(err){
  throw err;
}
console.log("savesuccess");
recall("写文件成功");
  });
}
}

========================

路由改造:文字和图片一起使用

var http = require('http');
var fs = require('fs');
var url = require('url');
var routes=require('./models/routes');
http.createServer(function (request, response) {
   var pathname = url.parse(request.url).pathname;
if(pathname!="/favicon.ico"){
  pathname=pathname.replace(/\//,"");// 吧/去掉
    routes[pathname](request,response);//根据路径分发路由,执行相应的程序
console.log("主程序执行完毕");
   }
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');

*******************路由

var optfile=require("../models/optFile");
function getRecall(req,res){
    res.writeHead(200, {'Content-Type': 'text/html'});
  function recall(data){
    res.write(data);//  发送响应数据,在网页上显示
    res.end("ok");// 如果没有这句话,则网页一直在加载,不完成;就没有http协议尾部
  }
  return recall;
}
module.exports={
login:function(req,res){
  //创建一个闭包,作为参数传过去
recall=getRecall(req,res);
// optfile.readfileSync("D:nodejs/views/login.html");//同步读取文件
optfile.readfile("D:nodejs/views/login.html",recall);//异步读取文件
},
regist:function(req,res){
  //创建一个闭包,作为参数传过去
recall=getRecall(req,res);
// optfile.readfileSync("D:nodejs/views/login.html");//同步读取文件
optfile.readfile("D:nodejs/views/regist.html",recall);//异步读取文件
},
//写文件
writeFile:function(req,res){
recall=getRecall(req,res);
  optfile.writeFile("D:nodejs/views/write.text","写文件",recall);
},
readImage:function(req,res){
recall=getRecall(req,res);
  optfile.readImage("D:nodejs/images/one.jpg",recall);
},
showImage:function(req,res){
      res.writeHead(200, {'Content-Type': 'image/jpeg'});
    optfile.readImage("D:nodejs/images/one.jpg",res);
}
}

******************操作

****************显示:

var fs=require('fs');//引入文件操作模块


module.exports={
readfileSync:function(path){
  var data=fs.readFileSync(path,'utf-8');//同步方法读取文件
  console.log(data);
  console.log('同步方法执行完毕');
},
readfile:function(path,recall){
  fs.readFile(path,function(err,data){
if(err){
  console.log(err);
}else {
  console.log(data.toString());
  recall(data);
}
  });
  console.log("异步方法执行完毕");
},
//读取图片
readImage:function(path,res){
 fs.readFile(path,"binary",function(err,data){
    if(err){
      console.log(err);
      return;
    }else {
    res.write(data,"binary");
    res.end("");
    }
  });
},
//异步写文件
writeFile:function (path,data,recall){
  fs.writeFile(path,data,function(err){
if(err){
  throw err;
}
console.log("savesuccess");
recall("写文件成功");
  });
}
}

<html>
<body>
<p>登陆</p>
<!-- 走到img这的时候会去请求服务器,走路由里再去执行showImage方法-->
<img src="./showImage"/>  <!--这一步会触发请求服务器-->
</body>
</html>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值