Obtaining an authorization token through a POST request and subsequently utilizing the POST response in a GET request

After requesting a Spotify access code using the POST method and storing the response in a variable, an attempt was made to access the token using the GET method immediately after.

   {
        angular.module('app')
            .controller('GameController', function($http){
                const $ctrl = this;

                $http.post('/access-token').then(function(response){
                    $ctrl.tokenResponse = response.data;
                    $ctrl.myToken = $ctrl.tokenResponse.access_token;
                    console.log(response);

                });

                   $http({
                    url: 'https://api.spotify.com/v1/tracks?ids=6rqhFgbbKwnb9MLmUQDhG6',
                    method: 'GET',
                    data: {
                        'Authorization': `Bearer ${$ctrl.myToken}`
                    }
                }).then(function(response){
                    console.log(response.data);
                    $ctrl.tracks = response.data;
                    console.log($ctrl.tracks);
                })

        });
    };

The issue arises when attempting to access the variables from the POST method using the GET method. The ${$ctrl.myToken} is showing as undefined in the "data":{"Authorization":"Bearer undefined"} section. However, logging the POST results before the GET method execution displays the access code correctly.

A solution is needed to make sure that the GET method can read the response from the POST method effectively.

All of this code resides in the controller component.

https://i.sstatic.net/6H2MM.png

Answer №1

Alright, I followed the advice given and tried it this way. Good news - I'm able to get my access token now! However, there seems to be a new issue with fetching the data. Nevertheless, I appreciate all the help so far! :)

{
angular.module('app')
    .controller('GameController', function($http){
        const $ctrl = this;

        $http.post('/access-token').then(function(response){
            $ctrl.tokenResponse = response.data;
            $ctrl.myToken = $ctrl.tokenResponse.access_token;

            $http({
                method: 'GET',
                url: 'https://api.spotify.com/v1/tracks?ids=6rqhFgbbKwnb9MLmUQDhG6',
                data: {
                    Authorization: `Bearer ${$ctrl.myToken}`
                }
            }).then(function(response){
                console.log(response.data);
                $ctrl.tracks = response.data;
                console.log($ctrl.tracks);
            })

        });



});

};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Help! I'm receiving a modal error message requesting an ID for the correct modal view. How can

Here's the code snippet I've been working on: <!DOCTYPE HTML> <html> <head> <title> EURO CATALOGO </title> <style> #myImg { border-radius: 5px; cursor: pointer; transition: 0.3s; } #myImg:hove ...

Tips for making a bookmark for your iframe content

Within this HTML code, there is a list element with the ID "about_ma" and an iframe named "page" that is initially hidden. <div id="navigation"> <ul id="nav"> <li id="about_ma"><a href="index1.php?name=about.php">Ab ...

A custom AngularJS directive that dynamically assigns a unique tag name based on a specified string value

Is there a way to create a custom tag similar to <h1> where I can specify the level as an attribute for nested templates to indicate the depth? An example implementation could be: .directive('hx', function() { return { restrict: &ap ...

The $().bind function will not function properly unless the document is fully loaded

Do I need to include $(document).ready() with $().bind? Here is the HTML portion: <head> <script type="text/javascript" src="jquery-1.10.2.min.js"></script> <script type="text/javascript" src=&quo ...

Invisible reCaptcha: The Unseen AJAX Request

I am having difficulty implementing the invisible reCaptcha on my website. I have followed these steps: header <!-- Invisible reCaptcha --> <script src="https://www.google.com/recaptcha/api.js" async defer></script> form.php <f ...

I am puzzled as to why I am receiving an undefined value for the jwt token even though it is supposed to

The server successfully stored the JWT token in cookies during services on localhost/8000 and sent response cookies to client services. However, when attempting to retrieve the cookies on client services at localhost/3000, it is showing as undefined. I hav ...

Leverage angular to dynamically update excel sheet with parsed data

Question: I am currently trying to pull data from a website using Angular and I would like to export this data into an Excel file. Additionally, I want the ability to update this file with more data in the future. Is there a library that can help achieve ...

What sets apart style.width and offsetWidth in HTML?

It caught my attention that the value of offsetwidth is slightly larger. The same occurs for style.height and offsetheight. ...

Ways to access reference data within the parent data map in Firebase

I'm having trouble making this code work properly. The issue I'm encountering is that the res.data() does not appear in the docs object. getProjects = async () => { const colRef = db.collection('parentCollection').orderBy('c ...

Are you interested in creating dynamic tables/models with Sequelize?

Currently, I am exploring a theoretical question before diving into the implementation phase. The scenario is as follows: In my application, users have the ability to upload structured data such as Excel, CSV files, and more. Based on specific requirement ...

Angular filtering with drop-down selection and input box

I'm dealing with an array of objects that have a boolean property, and I need to create a three-stage drop-down menu. This menu should allow users to view all items, only active items (those with the property set to true), or only trashed items (those ...

Tips for implementing a CSS style alteration upon clicking a button in a separate HTML page

I created JavaScript quizzes for my users to complete. Once they click the finished button at the end of the quiz, I want to highlight the box on the home page with a green outline to indicate completion. The complete button is located on the challenge1.ht ...

What causes the variance in outcomes between employing a literal string versus a local variable?

Here is a loop that I am working with: for (var key in criteria) { var exists = Object.keys(item).some(function(k) { return item[k] === "Test"; }) } Initially, this loop functions as expected and returns 15 trues based on the number of i ...

Another problem with CORS again?

My rails application uses the host http://myhost.dev to search for music through the vk.com API. The API provides a search method called audio.search. Below is the code snippet from my search.js.erb file which is executed via a remote link to the search ac ...

What causes a promise to be in a 'pending' state when the user logs out while the handler is being executed?

This puzzling inquiry delves into a non-practical issue but remains intriguing nonetheless: const r = Promise.resolve('I resolved') .then(() => { console.log('*****then*****') console.log( r ) console.log('*****the ...

What is causing the array elements to be iterated through multiple times?

My goal is to display all the titles from an array called 'title element' containing 10 values. However, I am encountering a problem: The for loop outputs all 10 values repeatedly 10 times. The titles are: Title 1, Title 2, Title 3, Title 4, T ...

Utilize JavaScript to target the specific CSS class

Hello, I am currently using inline JS in my Wordpress navigation menu, redirecting users to a login page when clicked. However, I have been advised to use a regular menu item with a specific class and then target that class with JS instead. Despite searchi ...

The issue with v-model on dynamically created inputs in Vue.js

I've spent the entire day searching, but I still haven't found a solution to this issue. I'm working on an app where I need to use v-model for reactive input that displays its value in another div element. What I really want is to be able t ...

Performing a JavaScript Axios POST request following a series of iterations using a while loop with

Just getting started with async/await and feeling a bit lost. I'm trying to figure out how to send an axios post request after a while loop finishes. Is there a way to wrap the while loop in an async function and await for it? Here's the code s ...

The function d3.json() does not support googleoverlay

As a newcomer to coding, I am currently working on incorporating the code found at https://bl.ocks.org/mbostock/899711. Instead of using a local .json file, I have opted to read JSON data from a URL. However, I encountered an issue where the LAT and LONG v ...