javascript - 创建一个在 HTTP 请求完成之前产生的函数
问题描述
我可以被认为是 Node.JS 的新手,所以很抱歉,在这里我试图创建一个产生代码执行的函数,直到代码完成发出 HTTP 请求(使用“请求”npm 模块),然后将返回,问题是该库不产生代码执行,我尝试过使用promise,但它仍然不会产生代码执行。
原始代码:
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=2&Subcategory=6&SortType=3&SortAggregation=5&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=2&Subcategory=6&SortType=3&SortAggregation=5&Category=6"))
使用承诺的输出:
C:\Program Files\nodejs\node.exe .\index.js
{}
resolving
解决方案
推荐阅读
- security - CSRF 如何获取某些网站的信息以利用安全性?
- c# - 如何在 ASP.NET 中编写 Excel 文件?
- python - 如何在 GeoDjango 中翻译多边形?
- reactjs - 服务器端渲染反应问题渲染子路由
- tabulator - 如何重新加载制表数据表中的数据?
- amazon-web-services - 如何将现场实例与亚马逊弹性豆茎一起使用?
- android - 改造:2 将模态数据发布到服务器
- ethereum - msg.sender 地址是否在作为参数传递给另一个合约时发生了变化?
- r - How to keep the value length in output file after division operation in R?
- reporting-services - 条件聚合查找 - SSRS