简体   繁体   English

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

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

Traditionally I use jQuery for all my JS code, but I'm tasked to launch a simple API with node.js. 传统上,我将jQuery用于所有的JS代码,但是我受命使用node.js启动一个简单的API。 Today is my first day with Node but I know enough about JS and closures to do OK. 今天是我在Node上的第一天,但​​是我对JS和闭包有足够的了解,可以做得到。 One of the tasks of the API is to authenticate across a third party service and being a python guy, I wanted to abstract all my outbound request calls like so: 该API的任务之一是通过第三方服务进行身份验证,并成为一名python专家,我想抽象所有出站请求调用,如下所示:

EDIT 编辑

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 As I said I don't know how node.js is supposed to be styled. @ jfriend00正如我说的,我不知道应该如何设置node.js的样式。 I wanted to just abstract as much as possible to make the code clean and reusable 我想尽可能地抽象一下,以使代码干净且可重用

Now when I do http://localhost:9000/latest/ 现在,当我执行http:// localhost:9000 / latest /

I get: 我得到:

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

Uhhh, this part will simply not work: 嗯,这部分根本无法工作:

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);
}

If result.statusCode is ever undefined , this will spin forever piling up setTimeout() calls in the event queue until eventually something fills up or you run out of memory. 如果result.statusCode始终undefined ,则它将永远旋转以堆积事件队列中的setTimeout()调用,直到最终某些内容耗尽或内存不足。

Because node.js is primarily single threaded, you can't loop waiting for something to change. 因为node.js主要是单线程的,所以您不能循环等待更改。 Because you never finish this while loop, no other node.js code gets to run so result.statusCode can never change. 因为您永远不会完成while循环,所以没有其他的node.js代码可以运行,因此result.statusCode永远都不会改变。 Thus, you have an infinite loop here. 因此,这里有一个无限循环。

All of your nodejs code needs to be event driven, not spin/wait loops. 您所有的nodejs代码都必须是事件驱动的,而不是旋转/等待循环。 FYI, this is similar to browser-based Javascript. 仅供参考,这类似于基于浏览器的Javascript。

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

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