javascript 用 request-promise 替换节点 request.post

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26013693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:22:25  来源:igfitidea点击:

Replacing node request.post with request-promise

javascriptnode.jspromise

提问by VB_

I have:I used Node.js request module to get authorization token:

我有:我使用 Node.js 请求模块来获取授权令牌:

Working code without promise

没有承诺的工作代码

var request = require('request');
var querystring = require('querystring');

var requestOpts = querystring.stringify({
    client_id: 'Subtitles',
    client_secret: 'X............................s=',
    scope: 'http://api.microsofttranslator.com',
    grant_type: 'client_credentials'
});

request.post({
    encoding: 'utf8',
    url: "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13",
    body: requestOpts
}, function(err, res, body) { //CALLBACK FUNCTION
    var token = JSON.parse(body).access_token;
    amkeAsyncCall(token);
});

I want:It takes some time to get that token. In turn I need makeAsyncCallfrom getToken callback. So I decide to use a request-promisefrom here.

我想要:获得该令牌需要一些时间。反过来,我需要makeAsyncCall从 getToken 回调。所以我决定使用 a request-promisefrom here

Problem:request-promise seems don't work for me at all.

问题:请求-承诺似乎对我根本不起作用。

The same (not working) code with promise:

与承诺相同(不工作)的代码:

    var rp = require('request-promise');
    var querystring = require('querystring');

    var requestOpts = {
        encoding: 'utf8',
        uri: 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13',
        method: 'POST',
        body: querystring.stringify({
            client_id: 'Subtitles',
            client_secret: 'Xv2Oae6Vki4CnYcSF1SxSSBtO1x4rX47zhLUE/OqVds=',
            scope: 'http://api.microsofttranslator.com',
            grant_type: 'client_credentials'
        })
    };

    rp(requestOpts)
    .then(function() {
        console.log(console.dir);
    })
    .catch(function() {
        console.log(console.dir);
    });

采纳答案by Thomas Gravel

I use the node.js package "unirest".

我使用 node.js 包“unirest”。

var unirest = require('unirest');
var dataObj = {};
var Request = unirest.post('http://127.0.0.1:' + port + '/test/4711DE/de');
Request.headers({ 'Accept': 'application/json' })                    
 .type('json')
 .send(JSON.stringify(dataObj))
 .auth({
   user: 'USERNAME',
   pass: 'PASSWORD',
   sendImmediately: true
 })
 .end(function (response) {
   assert.equal(200, response.statusCode);
   // ...
 });

回答by analog-nico

I tested your code with the latest version of Request-Promise(0.3.1) and it works fine.

我使用最新版本的Request-Promise(0.3.1)测试了您的代码,它运行良好。

Just the last part of logging to the console was not correct. Use:

只是登录到控制台的最后一部分是不正确的。利用:

rp(requestOpts)
    .then(function(body) {
        console.dir(body);
    })
    .catch(function(reason) {
        console.dir(reason);
    });

回答by Mu Hualing

You could set the jsonattribute in requestOptsbe true, it worksfor me.

你可以设置json在属性requestOptsBE true,它的作品对我来说。

var rp = require('request-promise');
var querystring = require('querystring');
var requestOpts = {
    encoding: 'utf8',
    uri: 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13',
    method: 'POST',
    json: true,
    body:    {
        client_id: 'Subtitles',
        client_secret: 'Xv2Oae6Vki4CnYcSF1SxSSBtO1x4rX47zhLUE/OqVds=',
        scope: 'http://api.microsofttranslator.com',
        grant_type: 'client_credentials'
    }
};

rp(requestOpts)
.then(function() {
    console.log(console.dir);
})
.catch(function() {
    console.log(console.dir);
});

回答by user2494388

I had the same issue I just added this property headers = { 'Content-Type': 'application/json' };

我有同样的问题,我刚刚添加了这个属性 headers = { 'Content-Type': 'application/json' };

var requestOpts = {
    encoding: 'utf8',
    uri: 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13',
    method: 'POST',
    headers = { 'Content-Type': 'application/json' };
    body: JSON.stringify({
        client_id: 'Subtitles',
        client_secret: 'Xv2Oae6Vki4CnYcSF1SxSSBtO1x4rX47zhLUE/OqVds=',
        scope: 'http://api.microsofttranslator.com',
        grant_type: 'client_credentials'
    })
};