如何将响应值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中强制执行同步。
您应该用承诺来封装代码
return new Promise((resolve, reject) => {
const req = http.request(options, (res) => {
res.setEncoding('utf8');
res.on('data', (d) => {
resolve(d);
})
});
req.on('error', (e) => {
reject(e);
});
req.write(data);
req.end();
})