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', async function(req, res) {
const code = req.query.code;
// TODO: Request Step 1: Obtain an access token
// in a production app you'll want to store this in some kind of persistent storage
access = await client.exchangeCode(code);
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', async function(req, res) {
// TODO: Request Step 2: Get vehicle information
const { vehicles } = await smartcar.getVehicles(access.accessToken);
// instantiate the first vehicle in the vehicle id list
const vehicle = new smartcar.Vehicle(vehicles[0], access.accessToken);
const attributes = await vehicle.attributes();
res.render('vehicle', { 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!