node.js - 将 Async/Await 与 npm 请求模块结合使用

标签 node.js asynchronous npm-request

我目前正在尝试使用 npm 请求模块发送一些请求。 普通的回调变体工作得很好,但我无法使用异步等待执行相同的操作。

起初,我尝试使用“request-promise-native”模块来完成此操作,但我什至无法运行正常的 Promise 示例。

var request = require('request-promise-native');
request(login)
        .then(function (response) {
            console.log("Post succeeded with status %d", response.statusCode);})
        .catch(function (err) {
            console.log("Error");
        });

我不确定我做错了什么,但 .then 函数被调用并且响应属性完全为空。如果我查看 webstorm 调试,我只会在该值中看到 giberisch �。截图:

enter image description here

我的最终目标是像这样使用 npm 请求模块:

var result = 等待请求(登录);

如果不可能的话,结果要么是响应,要么是错误,我也可以使用仅 promise 的变体。

有人可以告诉我我做错了什么或者如何正确地做吗?

问候 鲁维

编辑:好的,我发现第一个问题是什么。 我联系的服务器发送 gzip 信息,我需要将 gzip = true 放入我的选项对象中,现在我得到了一个可读的答案。 但我的问题没有解决:

如果我使用:

req(login, function(error, response, body){
        if (error)
         console.log(error);

        console.log(body);
        console.log(response.statusCode);
    });

我得到了完整的请求和响应对象。来自请求模块。 如果我使用:

 var result = await req(login);

我得到请求对象的结果,但没有响应对象和响应 header 信息。

这仅返回响应正文,仅填充一个变量:

request(login)
        .then(function (response, body) {
            console.log(response);})
        .catch(function (err) {
            console.log("Error");
        });

我如何获得 Promise 并等待返回整个请求+响应对象?

最佳答案

要获取完整的响应对象,您必须添加:resolveWithFullResponse=true 传递给请求函数的选项对象

如果您使用:

var request = require('request-promise-native');

var result = await request(login);
//or
request(login)
        .then(function (response, body) {
            console.log(response);})
        .catch(function (err) {
            console.log("Error");
        });

两者都工作正常,并且返回完整的请求/响应对象。

关于node.js - 将 Async/Await 与 npm 请求模块结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48643404/

相关文章:

c# - 如何在 .NET 4.0 中正确使用 async/await

node.js - 在nodejs-request中多次异步调用时获取原始请求对象

node.js - 将数据从 Node js Controller 连续流式传输到网页

javascript - 使用 cheerio(JQuery API)在 Node js 上解析

c# - 如果我返回一个任务而不等待任何事情,我应该使用异步吗

c# - 将DataTable异步拆分为多个Datatable

node.js - npm adduser 用户名或密码不正确

javascript - 根据编码的formData值设置 Node 请求头

node.js - 尝试添加 opencv 时 Heroku CI 构建失败,但应用程序部署有效

javascript - 用于异步 Linux 脚本的 Node.js