Node 处理 POST 和 GET请求

创建http 服务器

请求 http 的数据包

const http = require('http')

通过http创建服务器

// req => 请求 res => 响应
const server = http.createServer( (res,req) => {
	...
})

监听指定端口号

server.listen(4888,()=>{
    console.log('启动成功')
})

获取请求数据函数

// 获取请求的方法 GET or POST
const method = req.method;
console.log('method',method);
// 获取路径信息
const url = req.url
console.log('url',url)

请添加图片描述

获取带参数的url

  1. url 分为两个部分, ? 号前是访问网页的路径,后面是携带的参数,可以使用split来进行分割
  2. 使用工具来进行解析携带数据,比如 querystring
// import
const querystring = require('querystring')

// core code
const path = url.split('?')[0]
const query = querystring.parse(url.split('?')[1])
console.log(query)

访问http://localhost:4888/?name=hello&love=cat的结果为

[Object: null prototype] { name: 'hello' }

返回响应的数据

可以把返回的数据集成到一个const里面

 const resData = {
    method,
    url,
    path,
    query

返回数据到页面上

// 设置内容类型
res.setHeader('Content-Type','application/json')
/* Content-Type 用于定义网络文件的类型和网页的编码,
		决定浏览器将以什么形式、什么编码读取这个文件
*/
// 设置方法为 method 的时候才能进行
if (method === 'GET'){
        res.end(
            JSON.stringify(resData)
						// 只能返回字符串,所以要转换成字符串![请添加图片描述](https://img-blog.csdnimg.cn/3a4d608832cf4b7f9284cb40aec7d2e0.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAeGluZ3Blbmctemh1YW5n,size_20,color_FFFFFF,t_70,g_se,x_16)

        )
    }

处理POST请求

if (method === 'POST'){
  ...
	//  代码运行在这里
}

接收post发送的数据

var postData = '';
// 监听请求的data 数据
// 数据会以流的方式传输
req.on('data', chunk => {
    console.log(chunk.toString())
    postData += chunk.toString()
})

// 数据传输结束后,会读取end方法
req.on('end', () => {
		resData.postData = postData;
    console.log(resData)
})

// 传输结果
/*
{
  method: 'POST',
  url: '/',
  path: '/',
  query: [Object: null prototype] {},
  postData: '{\n\t"name":"cat",\n\t"love":"Miao"\n}'
}
*/

发送post数据

浏览器不能发送post请求,需要使用 postman 来进行发送post请求

请添加图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xingpeng-zhuang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值