Closed wentianl20 closed 5 years ago
Use a promise-based api, like got
, and then you can const response = await got(url)
instead of trying to get a callback interface to mesh with your async function
@wentianl20 I'm a bit concerned that both appid and secret looks real. I'm not at all aware what type of service you're requesting but I'd ensure that you haven't leaked credentials by mistake now.
As far as your problem goes, what you're experiencing is that the promise (which each mw of Koa is) resolves before the callback (thus response) from API service is called. You'll have to wrap that request in a promise and then return it (there's request-promise of the top of my head unless you'll want to do it yourself).
Here's a quick and dirty pseudo of how that could look.
...
if (!!query.code) {
...
return new Promise((resolve, reject) => {
request({
url: ...,
...
}, (err, response, body) => {
if (err) return reject(err)
ctx.body = body
resolve()
}
})
}
...
I'll close this for now as both responses should be sufficient as an answer. Please feel free to reopen if you're still experiencing issues.
Hi, I am fresh in Node.js and Koa. I just want to build a simple API. When a user calls this API, it can call a request with user's information and server's ID to a public API to get a token and then send back to the user. As the Koa does not supply a request function, I used the native request library. However, the callback function can't call the koa response correctly. I can print the token in my API, but I can't send it back to the user.