如何在Node.js中调用需要用户名和密码的API

我正在使用IBM Watson的Retrieve和Rank服务。 此服务提供了一个返回search结果的REST API。 以下是APIurl

https:// username:password@gateway.watsonplatform.net/retrieve-and-rank/api/v1/solr_clusters/sc6e46e4f5_f30c_4a8a_ae9c_b4ab6914f7b4/solr/example-collection/select?q =一些问题&wt = json&fl = id,title,body

正如你可以注意到这个URL需要一个用户名和密码。 Retreive和Rank文档提到了调用API的上述模式,即将用户名和密码作为URL的一部分。 如果我把它粘贴到谷歌浏览器中,它会popup对话框,再次input用户名和密码。 在input凭证后,我可以看到数据。

我的问题是,我怎么通过Node.js调用这样的URL。 我不知道从哪里开始,我应该遵循哪些步骤。

IBM Watson的Retrieve和Rank服务API使用基本authentication。 方式有几种,其中之一 – 使用模块request

 var url = "https://gateway.watsonplatform.net/retrieve-and-rank/api/v1/solr_clusters/sc1ca23733_faa8_49ce_b3b6_dc3e193264c6/solr/example_collection/select?q=what%20is%20the%20basic%20mechanism%20of%20the%20transonic%20aileron%20buzz&wt=json&fl=id,title" request.get('http://some.server.com/', { auth: { user: 'username', pass: 'password', sendImmediately: false }, json: true }, function(error, response, body) { console.log( 'Found: ', body.response.numFound ); }); 

要么

 var username = 'username', password = 'password', url = "https://" + user + ":" + password + "@" + "gateway.watsonplatform.net/retrieve-and-rank/api/v1/solr_clusters/sc1ca23733_faa8_49ce_b3b6_dc3e193264c6/solr/example_collection/select?q=what%20is%20the%20basic%20mechanism%20of%20the%20transonic%20aileron%20buzz&wt=json&fl=id,title" request({url: url, json: true}, function (error, response, body) { console.log( 'Found: ', body.response.numFound ); }); 

IBM Watson有一个您可能想要在您的应用程序中使用的节点SDK: https : //www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/retrieve-and-rank/api/v1/? node#

 var watson = require('watson-developer-cloud'); var retrieve_and_rank = watson.retrieve_and_rank({ username: '{username}', password: '{password}', version: 'v1' });