06-Node.js学习笔记-创建web服务器

创建web服务器

``` //引用系统模块 const http = require('http'); //创建web服务器 //用于处理url地址 const url = require('url'); const app = http.createServer(); //当客户端发送请求的时候 app.on('request',(req,res)=>{ //写入响应状态码 res.writeHead(200,{ 'content-type':'text/html;charset=utf8' }) //获取请求报文信息 //req.headers console.log(req.headers['accept']; //1.要解析的url地址 //2.将查询参数解析成对象形式 var params = url.parse(req.url,true).query; console.log(params.name); console.log(params.age); //获取请求地址 //req.url if(req.url =='/index'|| req.url=='/'){ res.end('

welcome to homepage柠檬不酸

'); }else if(req.url == '/list'){ res.end('welcome to listpage'); }else{ res.end('not found'); } //获取请求方式 //req.method console.log(req.method) if(req.method=="GET"){ res.end("GET") }else if(req.method=="POST"){ res.end("POST") } //响应 //res.end('

hi,user

'); }); //监听3000端口 app.listen(3000); console.log('服务器已启动,监听3000端口,请访问localhost:3000') ```

请求报文

1.请求方式(Request Method)

  • GET 请求数据
  • POST 发送数据

2.请求地址(Request URL)

``` app.on('request',(req,res){ req.headers //获取请求报文 req.url //获取请求地址 req.method //获取请求方法 }) ```

响应报文

1.HTTP状态码

  • 200请求成功
  • 404请求的资源没有被找到
  • 500服务器端错误
  • 400客户端请求有语法错误

2.内容类型

  • text/plain
  • text/html
  • text/css
  • application/javascript
  • image/jpeg
  • application/json

HTTP请求与响应处理

1.请求参数

客户端向服务器端发送请求时,有时需要携带一些客户信息,客户信息需要通过请求参数的形式传递到服务器端,比如登录操作

GET请求参数

参数被放置在浏览其地址中,例如:http://localhost:3000/?name=zhangsan&age=20

``` //用于创建网站服务器的模块 const http = require('http'); //用于处理url地址 const url = require('url'); //app对象就是网站服务器对象 const app = http.createServer(); //当客户端有请求来的时候 app.on('request',(req,res)=>{
console.log(req.method)
//1.要解析的url地址
//2.将查询参数解析成对象形式
let {query,pathname}= url.parse(req.url,true);
console.log(query.name);
console.log(query.age);
//写入响应状态码
res.writeHead(200,{
    'content-type':'text/html;charset=utf8'
})
if(pathname =='/index' ||pathname=='/'){
    res.end('<h2>欢迎来到首页</h2>');
}else if(pathname == '/list'){
    res.end('welcome to listpage');
}else{
    res.end('not found');
}
if(req.method=="GET"){
    res.end("GET")
}else if(req.method=="POST"){
    res.end("POST")
}

});
app.listen(3000);
console.log('网站服务器启动成功');

<h4>POST请求参数</h4>

1.参数被放置在请求体中进行传输
2.获取POST参数需要使用data事件和end事件
3.使用querystring系统模块将参数转换为对象格式

//用于创建网站服务器的模块
const http = require('http');
//app对象就是网站服务器对象
const app = http.createServer();
//处理请求参数模块
const querystring = require('querystring');
//当客户端有请求来的时候
app.on('request',(req,res)=>{
//post参数是通过事件的方式接收的
//data 当请求参数传递的时候触发data事件
//end 当参数传递完成的时候触发end事件

let postParams = ''
req.on('data',params=>{
    postParams +=params;
})
req.on('end',()=>{
    // console.log(querystring.parse(postParams))
    let params = querystring.parse(postParams);
    console.log(params.uname)
    console.log(params.password)
})

res.end('ok');
});
app.listen(3000);
console.log('网站服务器启动成功');

posted @ 2019-12-19 23:06  ヾ百毒不侵  阅读(189)  评论(0编辑  收藏  举报