gpt4 book ai didi

node.js - 如何等待请求响应并返回值?

转载 作者:太空宇宙 更新时间:2023-11-03 22:52:28 27 4
gpt4 key购买 nike

当我在node.js服务器中使用请求模块时,遇到一些问题,例如等待和返回。

我想在 requestController 处接收“responseObject”值。

为了解决这个问题,我已经搜索了最好的方法,但还是没有找到。

如何解决这个问题?

先谢谢了!! :)

================================================== =========================

var requestToServer = require('request');

function getRequest(requestObject) {

var urlInformation = requestObject['urlInformation'];
var headerInformation = requestObject['headerInformation'];

var jsonObject = new Object( );

// Creating the dynamic body set
for(var i = 0; i < headerInformation.length; i++)
jsonObject[headerInformation[i]['headerName']] = headerInformation[i]['headerValue'];

requestToServer({
url : urlInformation,
method : 'GET',
headers : jsonObject
}, function(error, response ,body) {
// todo response controlling
var responseObject = response.headers;
responseObject.body = body;
});
}

// Controlling the submitted request
exports.requestController = function(requestObject) {
var method = requestObject['methodInformation'];
var resultObject = null;

// Selecting the method
if(method == "GET")
resultObject = getRequest(requestObject);
else if(method =="POST")
resultObject = postRequest(requestObject);
else if(method == "PUT")
resultObject = putRequest(requestObject);
else if(method == "DELETE")
resultObject = deleteRequest(requestObject);

console.log(JSON.stringify(resultObject));
}

最佳答案

您可以通过以下方式使用回调

function getRequest(requestObject, callback) {
// some code
requestToServer({
url : urlInformation,
method : 'GET',
headers : jsonObject
}, function(error, response ,body) {
// todo response controlling
var responseObject = response.headers;
responseObject.body = body;
callback(responseObject);
});
}

还有

// Controlling the submitted request
exports.requestController = function(requestObject) {
var method = requestObject['methodInformation'];

// Selecting the method
if(method == "GET")
getRequest(requestObject, function(resultObject){
console.log(JSON.stringify(resultObject));
});

//some code
}

希望有帮助。

关于node.js - 如何等待请求响应并返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37771386/

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