[我首先在请求函数中创建了一个return
语句(我已经链接了图片),然后在console.log
之外创建了function
语句,但这没有成功。
我的服务器代码
var options = {
'method': 'POST',
'url': 'http://localhost:8080/ES_Part1/api/user/getUser',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'username': username,
'password': password
}
};
requestToApi(options, function(error, response) {
if (error) throw new Error(error);
console.log("Send form data to remote api and to return the user from Spring")
console.log(response.body);
return response.body
});
var fromapi = response.body;
res.end();
示例:
👨🏫如果您想在处理程序之外获取respose.body
,则可以在below下使用此代码:
// an example get function
app.get('/users', async(req, res) => {
var options = {
'method': 'POST',
'url': 'http://localhost:8080/ES_Part1/api/user/getUser',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'username': username,
'password': password
}
};
const result = new Promise((resolve, reject) => {
requestToApi(options, function(error, response) {
if (error) return reject(error);
return resolve(JSON.parse(response.body));
});
})
// make sure, to use async in your function
// because we're using await here
var fromapi = await result;
// It's working here
console.log(fromapi);
res.end();
})
👆上方的代码,仅是可用于读取response.body
的示例。如果您要处理上述代码中的错误,可以使用以下代码:
try {
// make sure, to use async in your function
// because we're using await here
var fromapi = await result;
// It's working here
console.log(fromapi);
} catch(ex) {
// print error response
console.log(ex.message);
}
希望它能对您有所帮助。
我建议您在此处使用基于Promise
的方法,而不是用于requestToApi
的回调样式。如果您使用的是request
软件包,则可以使用基于Promise
的版本。
替代解决方案是自己创建一个promise
,例如:
var requestToApiAsPromise = (options) => {
return new Promise((resolve, reject) => {
requestToApi(options, (error, response) => {
if (error) {
reject(error)
return
}
resolve(response.body)
})
})
}
然后您可以在中间件中使用此方法:
app.post("/checkUser", (req, res) => {
async function process() {
try {
var username = req.body.username
var password = req.body.password
var options = {...}
var response = await requestToApiAsPromise(options)
// response => response.body
// do whatever
res.end()
} catch (error) {
next(error)
}
}
process()
})
此方法使用async/await
,因此可以像执行同步操作一样编写代码,因此可以更轻松地进行异步调用并使它们在下一行执行之前“等待”。