Попытка ударить следующий http-auth код:аутентификации HTTP модуль, использующий запрос nodejs возвращения неопределенными тела
var auth = require("http-auth");
var basic = auth.basic({
realm: "Authentication required",
file: __dirname + "/../htpasswd"
});
http.createServer(basic, onRequest).listen(port);
Ниже приведен фрагмент кода, который ударять выше логики с request library из nodejs:
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);
}
);
Выход:
Отклик: не определено
тело: неопределенное
ошибки: гнездо вешает
Stack след:
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
onRequest вызывается из app.js так:
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);
router.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);
});
})
}
Можете ли вы опубликовать полную трассировку стека ошибок? – gnerkus
yup, я редактирую вопрос, чтобы включить трассировку стека – user3452275
Я смог воспроизвести ошибку. Можете ли вы опубликовать метод onRequest? – gnerkus