Fetch Protected Data from a Resource Server with an Access Token

Share this video with your friends

Social Share Links

Send Tweet

We're going to fetch a user with that token we exchanged the code parameter for in the previous lesson.

All we have to do is make a fetch request to the /user endpoint with an Authorization header that contains the token and then return the data. Like this Authorization: `Bearer ${token}

Instructor: [0:00] Replace the console.log with a call to fetchUser function, which takes the token and returns a list of users and we can respond with this list. Create the fetchUser function and start with a variable that stores the URL to the API endpoint for fetching user data from Github.

[0:28] Now use fetch to make a request to the endpoint, passing it to the URL. Set the headers to an object that contains the authorization header. The value of the authorization header should be prefixed with bearer, and actual value should be the token.

[0:47] Get to JSON data from the response and return the data. Hit to the browser, and before clicking the Authorize link, open the terminal. Click on Settings and make sure Preserve Log is checked. If we don't, we won't catch the printed user between redirects.

[1:08] Now, click the Authorize link, and even though the site redirects to the Index page, you still get the user payload in the console.