nodejs--http篇

nodejs--http篇


知识补充:
http协议:超文本传输协议,定义了服务器和客户端在通讯的时候应该如何发送和接受数据。

1)使用node.js 的http服务器。
var http=require("http");
http.createServer(function(req,res){//创建新的web服务器对象
   res.writeHead(200,{'content-Type':'text/plain'});//告诉客户,返回的内容是文本。
   res.end('hello world\n');//返回hello world给客户端
}).listen(3000,"127.0.0.1");//定义服务器的端口和主机
console.log('Server running at http://127.0.0.1:3000/');//将信息记录到控制台

将上面的内容保存到server.js文件中,然后再服务器中运行:
D:\nodejs>node server.js
Server running at http://127.0.0.1:3000/

然后到浏览器中输入:http://127.0.0.1:3000进行测试。
测试结果如下:
hello world



2)给http请求加入header:包括内容类型,响应日期,http状态码。
var http=require("http");
http.createServer(function(req,res){//创建新的web服务器对象
   res.writeHead(200,{'content-Type':'text/plain'});//告诉客户,返回的内容是文本。
   res.end('hello world\n');//返回hello world给客户端
}).listen(3000,"127.0.0.1");//定义服务器的端口和主机
console.log('Server running at http://127.0.0.1:3000/');//将信息记录到控制台



3)node.js重定向。
重定向的准则如下:
a 给客户发送301响应码,告诉用户,资源已经移到另外一个位置。
b 发送一个位置头(location header),告诉用户重定向到哪里。

var http=require('http');
http.createServer(function(req,res){
  res.writeHead(301,{'location':'http://www.baidu.com'});
  res.end();
}).listen(3000,"127.0.0.1");
console.log('server running at http://127.0.0.1');


4)响应不同的请求。
var http=require('http');
var url=require('url');
http.createServer(function(req,res){

  var pathname=http.parse(req.url).pathname;
  if(pathname==='/'){
     res.writeHead(200,{'Content-Type':'text/plain'});
     res.end('Home page\n');
  }else if(pathname==='/about'){
     res.writeHead(200,{'Content-Type':'text/plain'});
     res.end('About us\n');
  }else if(pathname==='/redirect'){
     res.writeHead(301,{'Location':'http://www.baidu.com'});
     res.end();
  }else{
     res.writeHead(404,{'Content-Type':'text/plain'});
     res.end('Page not found\n');
  }
   
}).listen(3000,"127.0.0.1");
console.log("server running at http://localhost:3000/");


4)使用node.js的http客户端。
使用http的客户端,可以使用http模块的http.get()方法来实现对服务器的get请求,而且需要指定一个包含了想要获取的页面的细节信息的option对象,细节包括主机,端口号,路径。

var http=require('http');
var options={
   host:'www.baidu.com',
   port:80,
   path:'/'
};

http.get(options,function(res){
    if(res.statusCode==200){
       console.log("this site is up!");
    }else{
       console.log("this site is down");
    }
}).on('error',function(e){

   console.log("there was an error:"+e.message);
});

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值