FED

©FrontEndDev.org
2015 - 2024
web@2.23.0 api@2.21.1

koajs--前端异步请求问题?

app.post('/signup',function* (){
        var body = yield parse(this),
            name = body.username,
            email = body.email,
            password = body.password,
            password_re = body.password_re;
            this.body = {
                msg:'创建成功!',
                status:1
            };
    });

前端代码

 petitspois.ajax = function(options){

            var pms = {},

                xhr = new XMLHttpRequest(),

                opts = (function(s, o){
                    var opts = {};
                    petitspois.mixIn(opts, s, o);
                    return opts;
                })(settings, options),

                param = function(data){
                    var s = [];
                    for(var key in data){
                        s.push(encodeURIComponent(key)+'='+encodeURIComponent(data[key]));
                    }
                    return s.join('&');
                },

                ready = function(resolve, reject){
                    console.log(xhr.status) //结果为0
                    if(xhr.status>=200 && xhr.status<300 || xhr.status === 304){
                        var data = (opts.dataType=='xml')?xhr.responseXML : xhr.responseText;
                        if(opts.dataType=='json'){
                            data = JSON.parse(data);
                        }
                        resolve(data, xhr.status);
                    }else{
                        reject(opts, xhr, xhr.status);
                    }
                };
            //clear cache
            if(!opts.cache){
                opts.url += (~opts.url.indexOf('?')?'&':'?')+'_='+ (+new Date);
            }

            //queryString
            if(opts.data){
                if(opts.type == 'GET'){
                    opts.url += (~opts.url.indexOf('?')?'&':'?')+ param(opts.data);
                    opts.data = null;
                }else{
                    opts.data = param(opts.data);
                }
            }

            xhr.open(opts.type, opts.url, opts.async);

            xhr.setRequestHeader('Content-type', opts.contentType);

            if(opts.dataType && opts.accepts[opts.dataType]){
                xhr.setRequestHeader('Accept', opts.accepts[opts.dataType]);
            }

            if(opts.async){
                pms = new Promise(function(resolve, reject){
                    xhr.onload = ready.apply(xhr, arguments);
                });
                xhr.send(opts.data);
            }else{
                xhr.send(opts.data);
                ready();
            }

            return pms;

        }

后端this.status = 200, 也是一样的结果。jquery也是一样