如何将响应值 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中强制执行同步。
答案 0 :(得分:0)
您应该使用承诺来封装代码
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();
})