Node
Request
Now that the Node 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 Node application must exchange the code
for an access_token
to make a request.
After receiving the access_token
, the user can be redirected to the /vehicle
route which we will implement in the next step.
// ./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 attributes
Once the application has the access_token
, it can send requests to a vehicle using Smartcar’s API.
Once we have the vehicle attributes, it is passed to the view defined in views/vehicle.hbs
which displays it in an HTML table.
// ./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 try out your app and see the data that Smartcar returns!