nodejs中的get,post请求

代码如下:

let http = require('http');

// 对url路径进行处理
let url = require('url');

let obj = [20, 20, 20, 20, 20, 20]
http.createServer((req, res) => {
    if (req.url === '/favicon.ico') return false;
    res.writeHead(200, {
        // text/html html字符串格式
        // text/plain 普通文本字符串
        'content-type': 'text/plain;charset=utf-8',
        // 允许跨域
        'Access-Control-Allow-Origin': '*'
    });

    // post请求
    if (req.method.toLowerCase() === 'post' && req.url === '/temp/PostAllParameter') {
        if (req.url === '/temp/PostAllParameter') {
            let alldata_ = '';
            req.on('data', function (chunk) {
                alldata_ += chunk;
            })
            req.on('end', function () {
                // 将传递过来拼接的字符串转化成一个数组
                alldata_ = new URLSearchParams(alldata_);
                console.log(alldata_);
                res.end(JSON.stringify(alldata_));
            })
        }
    }
    // get请求
    else {
        // let url_o = url.parse(req.url,true);
        let url_o = new URL(req.url, 'http://127.0.0.1:12601')
        if (url_o.pathname === '/add/') {
            res.write(url_o.searchParams.get('name') + url_o.searchParams.get('age'))
        } else if (url_o.pathname === '/temp/findAllParameter/') {
            res.write(JSON.stringify(obj))
        } else {
            res.end();
        }
        // url_o.query为传递的参数
        // console.log(url_o.searchParams.get('name'))
        res.end();
    }

}).listen(12601, '127.0.0.1', () => console.log('http://127.0.0.1:12601'))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值