React
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
After receiving the authorization code
, the React application must exchange it for an access_token
. To do so, we can send the code
to the back-end service which we will implement in a bit. Until then, let’s assume our back-end service contains an endpoint /exchange
that receives an authorization code
as a query parameter and exchanges it for an access_token
.
We can add this logic in our onComplete
callback -
// src/App.jsx
onComplete(err, code, status) {
// TODO: Request Step 1: Obtain an access token
return axios
.get(`${process.env.REACT_APP_SERVER}/exchange?code=${code}`);
}
Notice that our back-end service does not return the access_token
. This is by design. For security, our front-end should never have access to the access_token
and should always be stored in the back-end.
2. Get vehicle attributes
Once the back-end has the access_token
, it can send requests to a vehicle using the Smartcar API. The React app will have to send a request to the back-end service which in turn sends a request to Smartcar. We have to do this because our front-end does not have the access_token
.
Assuming our back-end has a /vehicle
endpoint that returns the information of a user’s vehicle, we can make this query in our onComplete
callback and set the state of the React app with the returned vehicle attributes -
// src/App.jsx
onComplete(err, code, status) {
// TODO: Request Step 2a: Get vehicle information
return axios
.get(`${process.env.REACT_APP_SERVER}/exchange?code=${code}`)
.then(_ => {
return axios.get(`${process.env.REACT_APP_SERVER}/vehicle`);
})
.then(res => {
this.setState({vehicle: res.data});
});
}
Now that we have the vehicle attributes, we can render a simple Vehicle
component that shows the vehicle attributes in a table -
// src/App.jsx
render() {
// TODO: Request Step 2b: Get vehicle information
return Object.keys(this.state.vehicle).length !== 0 ? (
<Vehicle info={this.state.vehicle} />
) : (
<Connect onClick={this.authorize} />
);
}
3. Back-end service
Now that our front-end is complete, we will need to create a back-end service that contains the logic for the /exchange
and /vehicle
endpoints.
Note: you can ignore the Try it out section of the Getting Started guide, and instead follow along with the next section of this guide.
Try it out
Make sure your back-end server is up and running. In your back-end directory -
export SMARTCAR_REDIRECT_URI=https://javascript-sdk.smartcar.com/v2/redirect?app_origin=http://localhost:3000
node index.js
To run the React app -
npm run start
Now you can go to localhost:3000
to see your React app running!