My app is built using NodeJS and express.
I'm calling a REST API using HTTPS but I need to return the server response and do something outside of the function with the response data. Can someone provide some insight as to how this can be achieved?
I've tried to use return but that doesn't bring it outside.
app.post('/session/login', (req, res) => {
let userId = req.body.loginUsername
let password = req.body.loginPassword
let userObj = {
userId: req.body.loginUsername,
password: req.body.loginPassword
}
// Login function to contact Work 10 API
function w10APISignIn (userObj) {
const postData = JSON.stringify({
'user_id': `${userObj.userId}`,
'password': `${userObj.password}`,
'persona': 'user',
'application_name': 'TEST'
})
let requestOptions = {
host: serverName,
port: 443,
path: '/api/v1/session/login',
rejectUnauthorized: false,
method: 'PUT',
headers: {
'Accept': '*/*',
'Content-Type': 'application/json',
'Content-length': postData.length
}
}
let loginRequest = https.request(requestOptions, function (response) {
console.log(`Server Status: ${res.statusCode}`)
let body = ''
response.setEncoding('UTF-8')
JSON.stringify(res.headers)
response.on('data', function (chunk) {
body += chunk
})
response.on('end', function () {
console.log(body)
// return JSON.parse(body)
})
})
loginRequest.on('error', (err) => {
console.error(err.message)
return err.message
})
loginRequest.write(postData)
loginRequest.end()
}
// This returns undefined (wsApiLoginObj)
let wsApiLoginObj = w10APISignIn(userObj)
console.log(wsApiLoginObj)
if (wsApiLoginObj) {
return res.redirect(302, `/session/home/${wsApiLoginObj.user.email}`)
} else {
console.log('There was an issue logging in.')
res.redirect(302, '/session/loginError')
}
})
This line: " let wsApiLoginObj = w10APISignIn(userObj) " Should result in wsApiLoginObj containing the server response but instead it's undefined.