nodeJs--http

1.用法示例

通过下面的用法,可以了解http用法。

'use strict';
let http = require('http');
let url = require('url');
let querystring = require('querystring')

/**
 * @description 创建服务器
 */
function createServer() {
    //注意:当我们在服务器访问网页时,我们的服务器可能会输出两次“get request”。那是因为大部分浏览器都会在你访问 http://localhost:8888/时尝试读取 http://localhost:8888/favicon.ico )
    let server = http.createServer((request, response) => {
        //解析请求路径
        let urlObj = url.parse(request.url)
        console.log(urlObj)
        //解析请求参数
        let queryObj = querystring.parse(urlObj.query)
        console.log(queryObj)
        //路由处理
        if (urlObj.pathname === '/testRequest') {
            //发送post请求
            postTest(response);
        } else if (urlObj.pathname === '/testPost') {
            //发送post请求, 接收并处理post data
            let jsonData = '';
            request.on("data", function(data) {
                jsonData += data
                console.log('接受数据中。。。');
            });
            request.on("end", function() {
                console.log('接受完成!');
                console.log(querystring.parse(jsonData));
            })
        } else {
            response.writeHead(200, {'Content-Type': 'text/plain'});
            response.write('hello nodeJs!')
            response.end();
        }
    })

    server.listen(8888);
    console.log('Server is running at http://127.0.0.1:8888/');
}

function postTest(response) {
    let postData = querystring.stringify({
            'msg': 'Hello World!'
        })
    //发送post请求localhost:8888/test并带上参数postData
    let options = {
        hostname: 'localhost',
        port: 8888,
        path: '/test',
        method: 'POST',
        headers: {
            'Content-Type': '"text/plain',
            'Content-Length': postData.length
        }
    };

    let req = http.request(options);

    req.write(postData);
    req.end()
}

module.exports = {
    createServer: createServer
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值