04 Nodejs-构建Web服务器

构建Web服务器

一、HPPT信息

(1) 通用头信息(General

  1. Request URL 请求的URL,向服务器端获取的内容
  2. Request Method 请求的方法,GET或POST
  3. Status Code 响应的状态码
  4. Remote Address 请求服务器的IP地址和端口号

状态码 分类:

200系列 : 服务器成功响应
300系列 : 响应的重定向, 跳转另一个URL
400系列 : 客户端错误
500系列 : 服务器错误

(2) 响应头信息(Response Headers

  1. Connection 连接方式
  2. Content-Type 响应文件类型
  3. Transfer-Encoding 响应时的传输方式

(3) 请求头信息(Request Headers

  1. Accpet 客户端接受的文件类型汇总
  2. Connection 客户端和服务器端的连接方式
  3. User-Agent 客户端使用的浏览器

二、HTTP模块

可模拟浏览器向服务器端发送请求,也可创建Web服务器

(1) 模拟浏览器

const http = require('http');
http.get('http://www.baidu.com/index.html',(res)=>{
    //res:响应的对象
    console.log(res.statusCode);//打印状态码
    //获取服务器端响应的数据
    res.on('deat',(buf)=>{
    //on('data'(buf)=>{}):当有数据传递时触发函数,buf接收响应数据
    	consol.log(buf);    
    });
});

(2) 创建Web服务器

const http = require('http');
//创建web服务器
var server = http.createServer();
//分配端口,监听端口
server.listen(3000,()=>{
   console.log("Web服务器创建成功!"); 
});

server.on('request',(req,qes)=>{
    //request,请求信息
    //req,请求的对象
    //res,响应的对象
    console.log(req.url);
    //设置响应内容
    res.writeHead(302,{
     Location:'http://www.baidu.com'               
   });
    //响应结束
    res.end();
});


发布了108 篇原创文章 · 获赞 167 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42873753/article/details/104195526
04