1

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.

  • Trying making your `w10APISignIn` into a promise, you can then do `w10APISignIn.then(wsApiLoginObj => ....)` – Keith Jun 18 '19 at 12:02
  • Can you please explain what you want to do? 1. Call a second API, return the response received from second API to user? 2. Call a second API, return the response received from second API to user? and then perform some action with that data? 3. Call a second API, return response irrelevant to response of second API to user and perform some action after that? – piyushkantm Jun 18 '19 at 13:47
  • which one of it is it? 1, 2 or 3? – piyushkantm Jun 18 '19 at 13:47
  • I need to return the object from the second API, access the properties and use those values to render the home page. – Lyndsey Boonekamp Jun 18 '19 at 22:55

0 Answers0