We'll be parsing the authorization code sent in our query before sending it to the server.
We do this by creating a function that parses our query and retrieves the code parameter. If we find a code in the query we send the code to our server by using fetch
to make a POST
request. In the body of the request we send the code and the state in stringified JSON.
Once we make the request we can await a response and store its JSON data (the auth token) in a variable. In a real application, we might also redirect to the homepage or the page the user was just on.
Instructor: [0:00] Add a handle code function in the onload function declaration. Go ahead and create this function. Create a variable called parse query inside the function to store the query from the URL which we can parse using the QS library.
[0:22] We only want to send the code to the server if the code exists in the URL. We can start with a check before calling the send code to server function.
[0:34] Now define the function and set the server URL to a variable. Create a TryCatch block and if there's an error, log the error to the console. Use fetch to make a request to the server endpoint.
[0:50] The method should be POST, and the body should be a JSON.stringify object. The object should contain the code, which we can get from the query, and optionally the state, which we can also get from the query. Set a Content-Type header, and the value should be application/JSON.
[1:10] When you get a response, parse it to JSON and log your response to the console. In a real application, you might also want to redirect to the home page or the page the user was on before the authentication flow. You can always store the user's URL in the OAuth state before starting the OAuth flow.
[1:31] Open the index.js file in the server folder. To confirm that the server receives the code, lock the request body to the console for inspection. Head back to the browser and click the authorize link.
[1:44] Notice how the code does not exist in the URL because you had been redirected back to the home page. Now, head back to the terminal to confirm that the code was actually sent to the server.