如何将响应值access_token返回给变量以供其他地方使用?如果我尝试在res.on('data')
侦听器之外记录其值,则会产生undefined。
const http = require('http');
const authGrantType = 'password';
const username = '[The username]';
const password = '[The password]';
const postData = `grant_type=${authGrantType}&username=${username}&password=${password}`;
const options = {
hostname: '[URL of the dev site, also omitting "http://" from the string]',
port: 80,
path: '[Path of the token]',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`); // Print out the status
console.log(`HEADERS: ${JSON.stringify(res.headers)}`); // Print out the header
res.setEncoding('utf8');
res.on('data', (access_token) => {
console.log(`BODY: ${access_token}`); // This prints out the generated token. This piece of data needs to be exported elsewhere
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
令牌值通过以下行记录到控制台:console.log(
BODY: ${access_token});
问题是试图提取此值以在其他地方使用。而不是必须在另一个调用中使用HTTP
调用来封装每个新函数,该调用需要取代它并在它可以继续之前向它提供响应。这是一种在NodeJS中强制同步的方式。
1条答案
按热度按时间wfsdck301#
你应该用promise封装你的代码