繁体   English   中英

使用Node.js抽象请求的生成

[英]Abstracting the making of requests with Node.js

传统上,我将jQuery用于所有的JS代码,但是我受命使用node.js启动一个简单的API。 今天是我在Node上的第一天,但​​是我对JS和闭包有足够的了解,可以做得到。 该API的任务之一是通过第三方服务进行身份验证,并成为一名python专家,我想抽象所有出站请求调用,如下所示:

编辑

var http = require('http');

var init = function(nconf) {
    var methods = {
    /*  
        Helper method to create the request header
    */
    headers: function(params) {
        var content = JSON.stringify(params);
        return {
            'Content-Type': 'application/json',
            'Content-Length': content.length
        }
    },
    /*
        Helper method to create the options object
        which is used in making any type of 
        outbound http request
    */
    options: function(host, path, method, params) {
         return {
            host: host,
            port: 80,
            path: path,
            method: method,
            headers: methods.headers(params)
        }
    },
    /*
        Helper method to abstract the making of
        outbound http requests
    */
    call: function(options, params, success, err) {
        var req = http.request(options, success);
        req.on('error', err);
        req.write(params);
        req.end();
    },
    /*
        Helper method to parse the response
        and return a json object
    */
    parse: function(res, result) {
        var responseString = '';
        res.on('data', function(data) {
            responseString += data;
        });

        res.on('end', function() {
            result = JSON.parse(responseString);
        });
    },
    /*
        API method to return the latest
        release and tag names
    */
    latest: function(req, res, next){
        // // var url = nconf.get('prod:authenticate');

        //authenticate the test user
        msg = methods.authenticate(nconf.get('test:user'), nconf.get("test:password"));
        res.send(msg);

        next();

    },
    /*
        Method used by this API to authenticate users.
        It is used to de-couple this API from the Database
        Schema by calling out to the TTCPAS App and requesting it
        to handle the authentication

    */
    authenticate: function(username, password){
        // create post parameters with API key
        var params = {"username": username, "password": password, "api_key": nconf.get('api_key')};
        //construct options object with params and header
        var options = methods.options(nconf.get('ttcpas:host'), nconf.get('ttcpas:auth_url'), 'POST', params);
        var result;
        var success = function(res) {
            res.setEncoding('utf-8');
            methods.parse(res, result);
        };
        methods.call(options, params, success, function(err){});
        while (typeof(result.statusCode) == 'undefined') {
            //wait 1 second;
            setTimeout(function(){
                console.log("waiting on request at " + nconf.get('ttcpas:host') + nconf.get('ttcpas:auth_url'));
            }, 1000);
        }
        //then down here
        if (result.statusCode == 200) {return result};//success
        if (result.statusCode == 403) {return "forbidden"};//forbidden


    }
}
return methods;
};
module.exports.init = init;

@ jfriend00正如我说的,我不知道应该如何设置node.js的样式。 我想尽可能地抽象一下,以使代码干净且可重用

现在,当我执行http:// localhost:9000 / latest /

我得到:

{"code":"InternalError","message":"first argument must be a string or Buffer"}

嗯,这部分根本无法工作:

while (typeof(result.statusCode) == 'undefined') {
    //wait 1 second;
    setTimeout(function(){
        console.log("waiting on request at " + nconf.get('ttcpas:host') + nconf.get('ttcpas:auth_url'));
    }, 1000);
}

如果result.statusCode始终undefined ,则它将永远旋转以堆积事件队列中的setTimeout()调用,直到最终某些内容耗尽或内存不足。

因为node.js主要是单线程的,所以您不能循环等待更改。 因为您永远不会完成while循环,所以没有其他的node.js代码可以运行,因此result.statusCode永远都不会改变。 因此,这里有一个无限循环。

您所有的nodejs代码都必须是事件驱动的,而不是旋转/等待循环。 仅供参考,这类似于基于浏览器的Javascript。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM