Fix bug in HTTP response parsing
This commit is contained in:
@@ -5,11 +5,16 @@ const log = new DebugBuilder("client", "httpRequests");
|
||||
require('dotenv').config();
|
||||
// Modules
|
||||
const http = require("http");
|
||||
const { isJsonString } = require("./utilities.js");
|
||||
|
||||
exports.requestOptions = class requestOptions {
|
||||
constructor(path, method, hostname = undefined, headers = undefined, port = undefined) {
|
||||
constructor(path, method, hostname = undefined, headers = undefined, port = undefined) {
|
||||
if (method === "POST"){
|
||||
this.hostname = hostname ?? process.env.SERVER_HOSTNAME ?? process.env.SERVER_IP;
|
||||
log.DEBUG("Hostname Vars: ", hostname, process.env.SERVER_HOSTNAME, process.env.SERVER_IP);
|
||||
if (hostname) this.hostname = hostname;
|
||||
if (process.env.SERVER_HOSTNAME) this.hostname = process.env.SERVER_HOSTNAME;
|
||||
if (process.env.SERVER_IP) this.hostname = process.env.SERVER_IP;
|
||||
if (!this.hostname) throw new Error("No server hostname / IP was given when creating a request");
|
||||
this.path = path;
|
||||
this.port = port ?? process.env.SERVER_PORT;
|
||||
this.method = method;
|
||||
@@ -31,31 +36,27 @@ exports.sendHttpRequest = function sendHttpRequest(requestOptions, data, callbac
|
||||
// Create the request
|
||||
const req = http.request(requestOptions, res => {
|
||||
res.on('data', (data) => {
|
||||
if (res.statusCode >= 200 && res.statusCode <= 299) {
|
||||
const responseObject = {
|
||||
"statusCode": res.statusCode,
|
||||
"body": JSON.parse(data)
|
||||
};
|
||||
log.DEBUG("Response Object: ", responseObject);
|
||||
callback(responseObject);
|
||||
}
|
||||
if (res.statusCode >= 300) {
|
||||
const responseObject = {
|
||||
"statusCode": res.statusCode,
|
||||
"body": data
|
||||
};
|
||||
log.DEBUG("Response Object: ", responseObject);
|
||||
callback(responseObject);
|
||||
}
|
||||
log.DEBUG("Response data from new node: ", data);
|
||||
const responseObject = {
|
||||
"statusCode": res.statusCode,
|
||||
"body": (isJsonString(data.toString())) ? JSON.parse(data.toString()) : data.toString()
|
||||
};
|
||||
log.DEBUG("Response Object: ", responseObject);
|
||||
callback(responseObject);
|
||||
})
|
||||
}).on('error', err => {
|
||||
log.ERROR('Error: ', err.message)
|
||||
if (err.code === "ECONNREFUSED"){
|
||||
// Bot refused connection, assumed offline
|
||||
log.WARN("Connection Refused");
|
||||
}
|
||||
else log.ERROR('Error: ', err.message, err);
|
||||
callback(undefined);
|
||||
// TODO need to handle if the server is down
|
||||
})
|
||||
|
||||
// Write the data to the request and send it
|
||||
req.write(data)
|
||||
req.end()
|
||||
req.write(data);
|
||||
req.end();
|
||||
}
|
||||
|
||||
exports.onHttpError = function onHttpError(httpStatusCode) {
|
||||
|
||||
Reference in New Issue
Block a user