Node.js — get与post请求

一、处理 get 请求

  1. nodejs 处理 http 请求

    • get 请求和 queryString
    • post 请求和 postData
    • 路由
  2. 简单示例

    // 1.导包
    const http = require("http");
    // 2.创建服务器
    const server  = http.createServer((reeq,res)=>{
        res.writeHead(200,{'content-type':'text/html'});
        res.end('<h1 style="color:red;">hello world</h1>');
    });
    // 3.开启监听服务器
    server.listen(6500,()=>{
        console.log('服务器已开启....6500');
    })
    
  3. nodejs 处理 get 请求

    • get 请求,即客户端要向server端获取数据,如查询博客列表
    • 通过 querystring 来传递数据,入 a.html?a=100&b=200
    • 浏览器直接访问,就发送 get 请求
  4. 代码

    // 1. 导包
    const http = require('http');
    const querystring = require("querystring");
    
    // 2. 创建服务器
    const server = http.createServer((req,res)=>{
        console.log(req.method) // 请求方法,GET
        const url = req.url // 获取请求完整的 url
        console.log("url",url);
        req.query = querystring.parse(url.split('?')[1]);   // 解析 querystring
        res.end(JSON.stringify(req.query));
    });
    
    // 3. 开启服务器监听
    server.listen(6400,()=>{
        console.log('服务器已开启')
    })
    
  5. 效果图

二、处理post请求

  1. nodejs处理post请求

    • post请求,即客户端要向服务端传递数据,如新建博客
    • 通过 post data 传递数据
    • 浏览器无法直接模拟,需要手写 js, 或者使用 postman
  2. 代码:

    const http = require('http');
    
    const server = http.createServer((req,res)=>{
        if(req.method === 'POST'){
            // 数据格式
            console.log('req content-type:',req.headers['content-type']);
            // 接收数据
            let postData = ''
            req.on('data',chunk =>{
                postData += chunk.toString();
            });
            req.on('end',()=>{ 
                console.log( 'postData:',postData)
                res.end('hello world') // 在这里返回,因为是异步
            })
        }
    });
    
    server.listen(6600,()=>{
        console.log('服务器已开启......')
    })
    
  3. 效果图

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值