node封装ajax

昨天看了一篇blog,大概知道了封装的过程,然后自己动手写了一下。

blog链接如下:https://blog.csdn.net/swl979623074/article/details/53302846

node源码的说明:https://nodejs.org/api/http.html#http_http_request_options_callback

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

let defaultConfig = {
    url: null,           // request url
    data: null,          // request data
    method: 'GET',      // request method  GET | POST
    encoding: 'utf-8',   // encoding-type utf-8 | gbk | ascii utf-8 is default
    headers: {},         // request headers
    timeout: 10,         // request timeout threshold (seconds)
    successFunc: function (data) {
    }, //request successfully
    errorFunc: function (data) {
    },   //request failed
};

function ajax(config) {
    if (typeof config !== 'object' || config === null || config === undefined) {
        console.log('params error');
        return;
    }
    if (config.url === null || config.url === undefined) {
        console.log("url cannot be null or undefined");
        return;
    }

    // update config
    for (let key in defaultConfig) {
        // dont not use '==='
        if (config[key] == null) {
            config[key] = defaultConfig[key];
        }
    }

    // parse url
    let params = URL.parse(config.url, true);

    // handle path
    params.path += '?';
    for (let key in config.data) {
        // encode URI component
        params.path += encodeURIComponent(`${key}=${config.data[key]}&`);
    }
    params.path += `$rand=${Math.random()}`;

    // set options
    let options = {
        host: params.host,
        port: params.port || 80,
        method: config.method,
        path: params.path
    };


    let req = http.request(options, function (res) {
        res.setEncoding(config.encoding);
        let data = '';
        res.on('data', function (chunk) {
            data += chunk;
        });
        res.on('end', function () {
            // encode URI component
            config.successFunc(decodeURI(data));
        })
    }).on('error', function (e) {
        config.errorFunc(e);
    });

    // POST
    if (config.method === 'POST') {
        let d = querystring.stringify(config.data);
        req.setHeader("content-length", Buffer.byteLength(d));
        for (let key in config.headers) {
            req.setHeader(key, config.headers[key]);
        }

        // write data to request body
        req.write(d);
    }

    //
    req.setTimeout(config.timeout);

    req.end();
}

exports.ajax = ajax;

//test
let test = require('./Ajax');

test.ajax({
    url: 'http://getman.cn/echo',
    data: {
        "msg": "hello world"
    },
    method: 'POST',
    headers: {
        "Content-Type": "application/json"
    },
    successFunc: function (data) {
        console.log(data);
    }
});

前端的道路还很长,继续进修!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Tina姐

我就看看有没有会打赏我

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

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

打赏作者

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

抵扣说明:

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

余额充值