【发布时间】:2016-03-06 19:25:44
【问题描述】:
尝试点击以下http-auth 代码:
var auth = require("http-auth");
var basic = auth.basic({
realm: "Authentication required",
file: __dirname + "/../htpasswd"
});
http.createServer(basic, onRequest).listen(port);
以下是使用nodejs的request library达到上述逻辑的sn-p代码:
var request = require('request'),
username = "username",
password = "password",
url = "http://localhost:3000/",
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
request(
{
url : url,
headers : {
"Authorization" : auth
}
},
function (error, response, body) {
console.log("body "+body);
console.log("response "+response);
console.log("error "+error);
}
);
输出:
响应:未定义
正文:未定义
错误:套接字挂断
堆栈跟踪:
events.js:141
throw er; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (_http_client.js:203:15)
at Socket.socketOnEnd (_http_client.js:288:23)
at emitNone (events.js:72:20)
at Socket.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:893:12)
at doNTCallback2 (node.js:429:9)
at process._tickCallback (node.js:343:17)
onRequest 方法:
module.exports.start = function(route, handle) {
function onRequest(request, response){
// response.write("welcome "+request.user+"!");
var pathname = url.parse(request.url).pathname;
route(handle, pathname, request, response);
}// on request ends here
从 app.js 调用 onRequest 如下:
var router = require("./lib/router.js");
var handle = {}
handle["/add"] = requestHandler.addMethod;
handle["/delete"] = requestHandler.deleteMethod;
handle["/edit"] = requestHandler.editMethod;
handle["/search"] = requestHandler.searchMethod;
console.log(router.route);
server.start(router.route, handle);
路由器.js
"use strict";
var url = require("url");
module.exports.route = function(handle, pathname, request, response) {
if(typeof handle[pathname] === 'function') {
handle[pathname](request, response);
} else {
console.log("no request handler found for "+pathname);
}// else ends here
}// route ends here
来自处理程序(requestHandler)的方法:
module.exports.addMethod = function (req, res) {
body = "";
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
body = JSON.parse(body);
databaseConnection.collection("productList").insert(body, function(err,data) {
if(err){
res.writeHead(400, {"contentType":"application/JSON"});
var failedRes = JSON.stringify({
error : {
text : "Failed to add product"
}
});
res.end(faileRes);
return;
}// error handling
res.writeHead(200, {"Content-Type": "application/JSON"});
var finalId = data.ops[0]._id;
var successRes = JSON.stringify({
data: {
id : finalId
},
error : {
code : 0,
text : "Product added successfully"
}
});
res.end(successRes);
});
})
}
【问题讨论】:
-
你能发布完整的错误堆栈跟踪吗?
-
是的,我正在编辑问题以包含堆栈跟踪
-
我已经能够重现该错误。可以发
onRequest方法吗? -
添加了onRequest方法
-
onRequest方法使用了route方法但是我不知道route方法的定义。你能把这个也发一下吗?
标签: javascript node.js httprequest http-authentication