gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:15:45 25 4
gpt4 key购买 nike

尝试点击以下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);
}
);

输出:

响应:未定义

正文:未定义

错误:套接字挂起

堆栈跟踪:

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

路由器.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);
});
})
}

最佳答案

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

JSON.parse(body);

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

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

或者,如果发送了数据:

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

这些错误都会导致服务器崩溃,从而导致客户端报告套接字挂起错误。

要解决此问题,您需要将数据以 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);
});

关于javascript - 使用nodejs的请求模块进行http认证返回未定义的主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35831441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com