使用Node.js进行基本的HTTP请求

I'm currently working on adding client-side testing to the Mozilla Developer Network (MDN).  I'm using Intern, a JavaScript-based WebDriver API created by my former employer SitePen.  MDN has used its own Persona login service for years, and since many key features of MDN require login (and subsequent account creation), it was important that I have a way to get test credentials.  There's a service that does provide those credentials, but that requires that I make a HTTP request from inside a test helper.

我目前正在为Mozilla开发人员网络(MDN)添加客户端测试。 我正在使用Intern ,这是由前雇主SitePen创建的基于JavaScript的WebDriver API。 MDN多年来一直使用其自己的Persona登录服务,并且由于MDN的许多关键功能都需要登录(以及随后的帐户创建),因此,我有一种获取测试凭据的方法,这一点很重要。 有一种服务确实提供了这些凭据,但是这要求我从测试助手内部发出HTTP请求。

I usually use the popular request module, available on npm, but I wanted to avoid external dependencies outside of the testing library.  I had always heard that dealing with HTTP requests with the native Node.js API was a nightmare, but after some investigation, I found what I needed was actually incredibly easy.  Here's a reduced, extremely simple example of making a HTTP request with Node.js:

我通常使用npm上流行的请求模块,但我想避免测试库之外的外部依赖关系。 我一直都听说使用本地Node.js API处理HTTP请求是一场噩梦,但是经过一番调查,我发现我所需的实际上非常简单。 这是一个通过Node.js发出HTTP请求的简化示例,它非常简单:


var http = require('http');

function getTestPersonaLoginCredentials(callback) {

    return http.get({
        host: 'personatestuser.org',
        path: '/email'
    }, function(response) {
        // Continuously update stream with data
        var body = '';
        response.on('data', function(d) {
            body += d;
        });
        response.on('end', function() {

            // Data reception is done, do whatever with it!
            var parsed = JSON.parse(body);
            callback({
                email: parsed.email,
                password: parsed.pass
            });
        });
    });

},


The only out of the ordinary part is the need to concatenate the incoming data stream, but apart from that, the process is actually pretty simple.  Of course you can add more checks for response status codes and the like, but there's a dead simple example of creating a HTTP request with the native Node.js code!

唯一不同寻常的部分是需要连接传入的数据流,但是除此之外,该过程实际上非常简单。 当然,您可以为响应状态代码等添加更多检查,但是有一个简单的示例,它使用本机Node.js代码创建HTTP请求!

翻译自: https://davidwalsh.name/nodejs-http-request

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值