如何使用Node.JS请求HTTP摘要authentication?
我必须用Node.JS编写一些API文档的代码,但是最近几天我尝试了所有可以在networking上find的解决scheme(包括当然是Stack),而没有成功…
我的API使用HTTP摘要authentication,这就是问题,我能够连接,这是不是一个大问题,但每次我得到相同的回报:
Got response : 401 HTTP Digest Authentication required for "api.example.com"
你可以在下面显示我的基本代码,而无需authentication! 因为我不知道我能做什么,
var http = require('http') var options = { host: 'api.example.com', path: '/example/1.xml', }; var request = http.get(options, function(res){ var body = ""; res.on('data', function(data){ body += data; }) res.on('end', function(){ console.log('Got response : ' + res.statusCode); console.log(body); }) res.on('error', function(e){ console.log('Got error : ' +e.message); }); });
我最后的一个尝试是使用这个模块https://npmjs.org/package/request,但他不工作,因为我每次得到401!
有关更多信息,我可以使用Ruby,Python,PHP和Java从我的API连接和获取所需信息,所以我确定我的API运行良好,并且我传递的信息是正确的。 我使用节点v0.10.11的最后一个稳定!
如果有人能帮助我或者有一个解决scheme,我会很高兴。
编辑:我会添加一些关于我的testing与模块Mickael /请求的细节
第一次尝试 :
var request = require('request') var options = { 'url': 'http://api.example.fr/example/1.xml', 'auth': { 'user': 'test', 'pass': 'test', 'sendImmediately': false } }; var request = request.get(options, function(error, response, body){ if (!error && response.statusCode == 200){ console.log('body : ' + body) } else{ console.log('Code : ' + response.statusCode) console.log('error : ' + error) console.log('body : ' + body) } });
第二次尝试:
var request = require('request') request.get('http://api.example.fr/example/1.xml', function(error, response, body){ if (!error && response.statusCode == 200){ console.log('body : ' + body) } else{ console.log('Code : ' + response.statusCode) console.log('error : ' + error) console.log('body : ' + body) } }).auth('test', 'test', false);
但是401的回报还是一样的
以下是您的示例更正为使用API的request
。
var options = { uri: 'http://api.example.fr/example/1.xml', auth: { user: 'test', pass: 'test', sendImmediately: false } }; request(options, function(error, response, body){ if (!error && response.statusCode == 200){ console.log('body : ' + body) } else{ console.log('Code : ' + response.statusCode) console.log('error : ' + error) console.log('body : ' + body) } });
请求可链接的风格的API有点混乱(恕我直言),但我相信你也可以使它的工作方式。
请求包中的摘要validation似乎不完整。
你可以试试: https : //npmjs.org/package/http-digest-client ,它是一个相当不错的轻量级实现摘要身份validation。
如果您需要使用要发送的正文消息进行摘要身份validation,则可以将请求与http-digest-client一起使用。 在安装之后,只需在node-modules下打开http-digest-client代码,并将http包的使用replace为请求包api。
- 使用passport.js将本地策略连接到另一个(Facebook,Twitter,Google等)
- 使用node.js,nano和CouchDB进行身份validation
- 设置passport-jwtauthentication
- 使用Facebook和Passportjs进行身份validation:什么是accessToken,注册后应该存储什么?
- 检查用户是否使用PassportJS / ExpressJSlogin
- 如何使用PassportJS与HapiJS
- 如何在Node.js中重新使用由Play Framework 2.2设置的签名cookie?
- LocalStrategy不是一个构造函数
- Passport是否支持新的Google+loginfunction?