来自具有HTTP基本身份验证(node.js)的应用程序的GET请求 [英] GET request from app with http basic authentication (node.js)
问题描述
我有一个nodejs应用,该应用在express.js中使用http基本身份验证.
I have an nodejs app which use the http basic authentication in express.js.
在此应用中,我向外部网页发出http.get请求以加载和解析html.
In this app I make an http.get request to an external webpage to load and parse the html.
通过基本身份验证,我在向外部主机发出的每个 http.get(url,function(){})
请求中得到一个错误:未经授权".如果我删除了基本身份验证,则可以正常工作.
With the basic auth I get in each http.get(url, function(){})
request to the external host an error: "Unauthorized". If I remove the basic authentication, it works fine.
有人知道,为什么只有我自己的服务器具有此身份验证,我才能在公共资源上未经授权?
Anybody know's why I'm Unauthorized at an public resource if only my own server has this authentication?
例如(伪代码):
通过快速基本身份验证,我从google.com上获得未授权"作为正文.没有身份验证,我得到了html
with the express basic authentication, I'm getting "Unauthorized" as body from google.com. without the auth, I get the html
var auth = express.basicAuth(function(user, pass, callback) {
var result = (user === 'john' && pass === 'doe') ? true : false;
callback(null, result);
});
app.configure(function(){
app.use("/", auth, function(next) { next(); });
app.use("/", express.static(__dirname+'/html'));
});
http.get('http://google.com', function(res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function (chunk) {
body = body + chunk;
});
res.on('end', function() {
cb(body);
});
}).on('error', function(err) {
cb('error', err);
});
推荐答案
在向服务器发出GET之后,您需要重组应用程序以在回调中完成对Google的调用.这是工作代码:
You need to restructure your app to have your call to Google done inside a callback, after a GET is issued to your server. Here's working code:
var express = require('express');
var request = require('request');
var app = express();
// Authenticator
app.use(express.basicAuth('john', 'doe'));
app.get('/', function(req, res) {
request.get('http://www.google.com', function (err, response, body) {
res.send(body)
});
});
app.listen(process.env.PORT || 8080);
如果要进行更高级的基本身份验证,请参见以下详细信息: http://blog.modulus.io/nodejs-and-express-basic-authentication
Here are details if you want to do fancier basic authentication: http://blog.modulus.io/nodejs-and-express-basic-authentication
您似乎正在尝试同步编写代码,这将无法正常工作.我建议阅读这篇文章以复习惯用节点: http://blog.ponyfoo.com/2013/07/12/teach-yourself-nodejs-in-10-steps
It appears that you're trying to write code synchronously, which will not work. I recommend reading this article for a review of idiomatic Node: http://blog.ponyfoo.com/2013/07/12/teach-yourself-nodejs-in-10-steps
这篇关于来自具有HTTP基本身份验证(node.js)的应用程序的GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!