客户端发送请求的方式以及服务端接收请求

客户端用get方式发送请求

 fetch("http://localhost:9000").then(data => {//发送请求

            return data.json();//接收过来的数据对象

        }).then(res => {console.log(res)})//接收过来的数据

服务端接收get请求

http.createServer((require, resporson) => {
    resporson.writeHead(200, {
        'Content-Type': 'text/html;charset=utf-8',//发送数据编码格式
        "Access-Control-Allow-Origin": "*"//解决本地跨域问题
    });
   
res.end("{"name":"张三"}")//响应数据

}).listen(9000, (err) => {
    if (!err) {
        console.log("服务器启动成功");

    }
})

客户端用post方式发送请求



   
    <script>
       
        
        let url = "http://127.0.0.1:9000"//要请求的地址
       
            fetch(url, {
                method: "POST",//请求的方式
                body: `username=${nameVal}&pwd=${pwdVal}&tel=${PhoneVal}`//要请求的数据
            }).then(data => {
                
                
                
              return data.text();//请求过来的数据对象
            }).then(res => {
                console.log(res)//请求过来的数据

            )

        }
    </script>

服务端接收响应请求

http.createServer((req, res) => {
    res.writeHead(200, {
        'Content-Type': 'text/html;charset=utf-8',
        "Access-Control-Allow-Origin": "*"
    });
    let str = ""
    req.on("data", (strs) => {

        str += strs //拼接buffs数据,保证完整
    })
    req.on("end", () => {
       
        
                res.end(str);
               
            

    })



    
}).listen(9000, (err) => {
    if (!err) {
        console.log("启动成功");

    } else {
        console.log(err);

    }
})

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

new 前端

请博主喝杯咖啡吧!

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

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

打赏作者

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

抵扣说明:

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

余额充值