Express

Request

Now that the Express application has an authorization code, it can exchange it for an access_token required to make a request to a vehicle.


1. Obtain an access token

In the previous section, we retrieved an authorization code. The Express application must exchange the code for an access_token to make a request.

The access_token represents your application's access to a vehicle on behalf of the vehicle owner.

After receiving the access_token, the user can be redirected to the /vehicle route which we will implement in the next step.

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
// ./index.js

// global variable to save our accessToken
let access;

app.get('/exchange', function(req, res) {
  const code = req.query.code;

  // TODO: Request Step 1: Obtain an access token
  return client.exchangeCode(code)
    .then(function(_access) {    
      // in a production app you'll want to store this in some kind of persistent storage
      access = _access;

      res.redirect('/vehicle');
    })
});

2. Get vehicle information

Once the application has the access_token, it can send requests to a vehicle using Smartcar's API.

Once we have the vehicle information, it is passed to the view defined in views/vehicle.hbs which displays it in an HTML table.

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
// ./index.js

app.get('/vehicle', function(req, res) {
  // TODO: Request Step 2: Get vehicle information
  return smartcar.getVehicleIds(access.accessToken)
    .then(function(data) {
      // the list of vehicle ids
      return data.vehicles;
    })
    .then(function(vehicleIds) {
      // instantiate the first vehicle in the vehicle id list
      const vehicle = new smartcar.Vehicle(vehicleIds[0], access.accessToken);

      return vehicle.info();
    })
    .then(function(info) {
      res.render('vehicle', {
        info: info,
      });
    });
});

Try it out

Make sure the server is running -

  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
  • $
node index.js

Now you can go to localhost:8000/login to see your Express app running!


Next steps