【问题标题】:http authentication using request module of nodejs returning undefined body使用 nodejs 的请求模块返回未定义正文的 http 身份验证
【发布时间】: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


【解决方案1】:

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

JSON.parse(body);

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

语法错误:输入意外结束
在 Object.parse(本机)

或者,如果数据已发送:

SyntaxError: Unexpected token ...
在 Object.parse(本机)

这些错误中的任何一个都会导致服务器崩溃,从而导致客户端报告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);
});

【讨论】:

  • 这不可能,因为我什至没有点击 addMethod 路线。我也检查过了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-11
  • 1970-01-01
  • 2018-10-15
  • 1970-01-01
  • 2021-07-05
  • 2013-06-15
  • 1970-01-01
相关资源
最近更新 更多