【问题标题】:NodeJs POST request not workingNodeJs POST请求不起作用
【发布时间】:2017-06-22 15:34:31
【问题描述】:

假设我有一个网址

https://someAPI.com/authorize?x=val1&y=val2

其中 x 和 y 是我发送的有效负载值 我怎样才能以这种方式进行发布请求?

我试过这个:

var https = require('https')

var options = {
    url: 'https://someAPI.com/authorize?x=val1&y=val2',
    method: 'POST',
    headers: {
         ....
    }
}

https.request(options, function(res) {
    var str = ""
    res.on('data', function(data){
        str+=data
    })
    res.on('end', function() {
        console.log(str)
    })
})

我没有得到任何回报。我做错了什么?

编辑:这是我认为的格式:

REQUEST
POST https://someAPI.com/us/oauth/v2/authorize?response_type=code&client_id=blahblahblah&redirect_uri=someOtherSite.com HTTP/1.1
Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
User-Agent: RestSharp/105.2.3.0
Content-Type: application/x-www-form-urlencoded
Host: someAPI.com
Content-Length: 98
Accept-Encoding: gzip, deflate

username=someuser&password=somepassword&action=Log%20In&sessionID=someSessionId

【问题讨论】:

  • require('https) 中缺少的' 是您的问题中的拼写错误还是您的代码中的逐字记录?
  • 这是我帖子中的错字。我会解决的。
  • url 怎么样?不应该是string吗?
  • 很难说为什么 unspecified API 不能从明显抽象的而不是真实的数据中为您提供您期望的结果。我们不知道它希望您发送什么。
  • 我相信我正在运行最新版本

标签: javascript https request


【解决方案1】:

变化:

https.request(options, function(res) {
    var str = "";
    res.on('data', function(data){
        str+=data;
    });
    res.on('end', function() {
        console.log(str);
    });
});

收件人:

var apiCall = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);

    res.on('data', (d) => {
        process.stdout.write(d);
    });
});

apiCall.on("error", (e) => {console.error(e)});
apiCall.end();

【讨论】:

  • 好酷!这将返回 html。状态码为 500。我知道这不好,但我认为这与我的凭据有关,而不是与请求有关。非常感谢。
  • 文档显示了为选项传递的不同值。我会看看nodejs.org/api/https.html#https_https_request_options_callback
  • 看起来它只需要一个完全编码的 URL(如连接字符串),或者您将值传递给像 {port: 443} 这样的对象,以便它可以构建 URL
  • 那么,看看我上面所做的编辑。最后一行是凭据。你是说我应该将它们作为自己的值传递,有点像标题?
  • 你可以做任何一个,你需要给它值来制作 url 或提供完整的 url。我更喜欢对象方法,因为它的工作量更少而且更容易编辑。查看此链接:nodejs.org/api/http.html#http_http_request_options_callback,您可以看到接受的键/值。看起来有一个 AUTH 适合你
猜你喜欢
  • 2017-02-23
  • 1970-01-01
  • 1970-01-01
  • 2018-12-25
  • 1970-01-01
  • 2016-03-27
  • 2017-01-05
  • 2016-11-05
相关资源
最近更新 更多