Node.js request模块获取refresh_token后无法返回值问题求助
Hey Adrian, the core issue here is asynchronous execution—the request library uses callback-based logic, which means your token isn't ready yet when you try to pass it to other parts of your code. Let me break this down and show you how to fix it.
The Problem with Callback-Based Code
When you run your current code, the request function kicks off the HTTP request and immediately moves on to the next line of code (if any) before the server sends back a response. By the time your callback logs the token to the console, any code trying to "return" or use that token has already finished running—so it gets nothing but an undefined value.
Solution 1: Wrap the Request in a Promise
You can convert the callback-based request call into a Promise, which lets you use async/await to handle the asynchronous result cleanly. Here's how to refactor your code into a reusable function:
var request = require("request"); // Wrap the token request in a function that returns a Promise function getRefreshedToken() { return new Promise((resolve, reject) => { var options = { method: 'POST', url: 'https://YOUR_DOMAIN/oauth/token', headers: {'content-type': 'application/x-www-form-urlencoded'}, form: { grant_type: 'refresh_token', client_id: 'YOUR_CLIENT_ID', client_secret: 'YOUR_CLIENT_SECRET', refresh_token: 'YOUR_REFRESH_TOKEN' } }; request(options, function (error, response, body) { if (error) { reject(new Error(error)); // Pass errors to the caller return; } resolve(JSON.parse(body)); // Resolve with the parsed token data }); }); } // Now you can use this function elsewhere with async/await async function useTokenInLogic() { try { const tokenData = await getRefreshedToken(); console.log("Token ready for use:", tokenData); // Use tokenData.access_token in your other API calls or auth logic here } catch (err) { console.error("Failed to refresh token:", err); } } // Call the function to trigger the token refresh useTokenInLogic();
Solution 2: Use a Promise-Based HTTP Library (Recommended)
The request library is actually deprecated now. For cleaner, more modern code, use a library like axios which supports Promises natively:
First install axios via npm:
npm install axios
Then rewrite your token request with axios:
const axios = require("axios"); async function getRefreshedToken() { try { const response = await axios.post( 'https://YOUR_DOMAIN/oauth/token', new URLSearchParams({ grant_type: 'refresh_token', client_id: 'YOUR_CLIENT_ID', client_secret: 'YOUR_CLIENT_SECRET', refresh_token: 'YOUR_REFRESH_TOKEN' }), { headers: {'content-type': 'application/x-www-form-urlencoded'} } ); return response.data; } catch (err) { throw new Error(`Token refresh failed: ${err.message}`); } } // Example usage in your main logic async function runMyAppLogic() { const token = await getRefreshedToken(); // Use the token for authenticated requests console.log("Using refreshed token:", token.access_token); } runMyAppLogic();
Key Notes
- Always handle errors properly (using
try/catchwith async/await, or.catch()with Promises) to avoid unhandled exceptions crashing your app. - Never hardcode sensitive values like
client_secretorrefresh_tokenin your code—use environment variables (e.g.,process.env.CLIENT_SECRET) instead to keep them secure.
内容的提问来源于stack exchange,提问作者Adrian Sultu

