使用nodejs的请求模块返回未定义主体的http认证

时间:2016-03-06 19:25:44

标签: javascript node.js httprequest http-authentication

尝试点击以下http-auth代码:

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);
    }
);

输出:

回复:未定义

body: undefined

错误:套接字挂断

堆栈跟踪:

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);

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);
        });
    })
}

1 个答案:

答案 0 :(得分:0)

由于服务器上出现JSON.parse错误而发生错误。 body对象是一个字符串,但它不是有效的JSON字符串。这导致行:

JSON.parse(body);

在服务器上抛出错误(如果没有发送数据):

  

SyntaxError:意外的输入结束
      在Object.parse(native)

或者,如果发送了数据:

  

SyntaxError:意外的令牌......
      在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);
});