使用Node.js提取请求的制作

时间:2015-02-07 16:34:28

标签: javascript jquery 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"}

1 个答案:

答案 0 :(得分:0)

呃,这部分根本不起作用:

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。