#javascript #node.js #node-request
Вопрос:
Меня можно считать новичком в Node.JS поэтому приношу извинения, здесь я пытаюсь создать функцию, которая обеспечивает выполнение кода до тех пор, пока код не завершит выполнение HTTP-запроса (с использованием модуля npm «запрос»), который затем будет возвращен, проблема в том, что библиотека не обеспечивает выполнение кода, я пытался использовать обещание, но оно все равно не приведет к выполнению кода.
Исходный код:
const request = require("request")
// CONFIG
const ROBLOSECURITY = ""
var http_header = {
"Cookie": ".ROBLOSECURITY=" ROBLOSECURITY
}
function MakeRbxReq(http_method, url, payload) {
var jsonbody
var retfunc = {}
try {
jsonbody = JSON.stringify(payload)
} finally {}
var options = {
uri: "http://" url,
body: jsonbody || "",
methpd: http_method,
headers: http_header
}
request(options, function(_, res) {
if (http_method.toUpperCase() == "POST" || http_method.toUpperCase() == "PUT" || http_method.toUpperCase() == "PATCH" || http_method.toUpperCase() == "DELETE") {
if (res.headers["X-CSRF-TOKEN"]) {
http_header["X-CSRF-TOKEN"] = res.headers["X-CSRF-TOKEN"]
options["headers"] = http_header
if (res.statusCode == 403) {
request(options, function(_, res) {
retfunc = {statusCode: res.statusCode, body: res.body}
})
} else {
retfunc = {statusCode: res.statusCode, body: res.body}
}
}
}
retfunc = {
statusCode: res.statusCode,
body: res.body
}
return
})
return retfunc
}
console.log(MakeRbxReq("GET", "search.roblox.com/catalog/json?CatalogContext=2amp;Subcategory=6amp;SortType=3amp;SortAggregation=5amp;Category=6"))
Попытка обещания:
const request = require("request")
// CONFIG
const ROBLOSECURITY = ""
var http_header = {
"Cookie": ".ROBLOSECURITY=" ROBLOSECURITY
}
function MakeRbxReq(http_method, url, payload) {
var jsonbody
var retfunc = {}
try {
jsonbody = JSON.stringify(payload)
} finally {}
var options = {
uri: "http://" url,
body: jsonbody || "",
methpd: http_method,
headers: http_header
}
async function req() {
let reqPromise = new Promise(function(resolve, reject) {
request(options, function(err, res) {
console.log("resolving")
resolve({statusCode: res.statusCode, body: res.body})
})
})
}
req()
return retfunc
}
console.log(MakeRbxReq("GET", "search.roblox.com/catalog/json?CatalogContext=2amp;Subcategory=6amp;SortType=3amp;SortAggregation=5amp;Category=6"))
Результат использования обещания:
C:Program Filesnodejsnode.exe .index.js
{}
resolving