cocos creator 的http请求 记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010971754/article/details/83992477

关于cocos的http请求,官网给的只有get方式。后来自己因为需要,要加一个post,各种尝试都不行,服务端一直接收不到信息。
今天这里做个备忘。
不多说,直接上代码:

/**
 * 新版接口
 * @example 使用 var Http = require('Http')
 * @example      new Http().Get(url, cb)//url链接 回调函数
 * @example      new Http().Post(url, param, cb)//url链接 param参数(json对象) 回调函数
 */
class CusHttp {
    constructor () {
        this._http
        this._callback
        this._event = CusEvent.getInstance()
    }
    /**
     * Get 请求
     * @param {*} Url 
     * @param {*} cb 
     */
    Get (Url, cb) {
        Com.info(Url)
        let http = cc.loader.getXMLHttpRequest();
        http.open("GET", Url, true)
        http.setRequestHeader("Content-Type","text/plain;charset=UTF-8");
        this._callback = cb;
        http.onreadystatechange = this._result.bind(this)
        http.timeout = 10000
        http.send()
        this._http = http
    }
    Post (Url, data, cb) {
        Com.info(Url)
        data = JSON.stringify(data)//以前不懂要怎么传,是缺少这一步
        let http = cc.loader.getXMLHttpRequest();
        http.open("POST", Url, true)
        http.setRequestHeader("Content-Type","text/plain;charset=UTF-8");
        this._callback = cb;
        http.onreadystatechange = this._result.bind(this)
        http.timeout = 10000//超时10秒
        http.send(data)
        this._http = http
    }
    _result () {
        if (this._http.readyState == 4 && this._http.status != 500) {
            let data = Global.StrToJSON(this._http.responseText).data
            Com.info('httpCall->', this._http.responseText)
            if (this._callback) {
                //如果服务端有回执text字段,则显示飘字
            }
        } else {
            Com.error('请求失败')
        }
    }
}
module.exports = CusHttp

我的服务端是用nodejs 的express写的。

router.post('/xxx', function (req, res, next) {
    req.on('data', function (data) {//需要用这样的方式来接收数据,这个是后来百度到的,其他的方式,我也还不清楚有没有
        var param = JSON.parse(data.toString())
        var content = param.content
        var device = param.device
        var time = Date.parse(new Date())
    })
});

 这套本人亲测,是行得通的。

 更多干货,可以到本人的小博客 it菜鸟

qq群:331260613,一起分享经验交流

猜你喜欢

转载自blog.csdn.net/u010971754/article/details/83992477