2016-03-06 5 views
1

Попытка ударить следующий 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); 
     }); 
    }) 
} 
+0

Можете ли вы опубликовать полную трассировку стека ошибок? – gnerkus

+0

yup, я редактирую вопрос, чтобы включить трассировку стека – user3452275

+0

Я смог воспроизвести ошибку. Можете ли вы опубликовать метод onRequest? – gnerkus

ответ

0

Ошибка возникает из-за JSON.parse Ошибка на сервере. Объект body является строкой, но это не действительная строка JSON. Это приводит к линии:

JSON.parse(body); 

бросить ошибку на сервере (если не данные были отправлены):

SyntaxError: Unexpected end of input
at Object.parse (native)

или, если был послан данные:

SyntaxError: Unexpected token ...
at Object.parse (native)

Любой из эти ошибки приводят к сбою сервера и, следовательно, к клиенту сообщать об ошибке socket hang up.

Для решения этой проблемы вам необходимо отправить данные на сервер как JSON. Для этого с модулем request:

request.post(url, { 
    headers: { 
     "Authorization" : auth 
    }, 
    json: { 
    message: 'Hello' 
    } 
}, function (error, response, body) { 
    console.log("body "+body); 
    console.log("response "+response); 
    console.log("error "+error); 
}); 
+0

Это не может быть правдой, потому что я даже не нахожусь в пути addMethod. И я тоже это проверил. – user3452275

Смежные вопросы