Vue Service - 401 (Access Denied)

Whenever I attempt to execute the "getUserData" method, it results in a 401 (Unauthorized) error. Strangely enough, when I make a GET request to the URL "" with the same headers in Postman, it works perfectly fine! How can I properly set my request headers?

this.$http.get('http://ppstemp.com/api/User/Profile',{params:{
        n: ...
      }} , {
          headers: {
            "Authorization": "bearer "+ localStorage.getItem('token') ,
            "Accept": "application/json",
            "cache-control": "no-cache"
          }
        }).then(
             (response) => {
               // Handle data returned
                console.log(response.data);
            },
            //error callback
            (err) => console.log(err));
        }

Answer №1

When using Vue resource's get method, the signature should be structured like this:

this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);

Make sure to include parameters along with the headers object in your request.

this.$http.get('http://ppstemp.com/api/User/Profile', {
  params: {
    n: ...
  },
  headers: {
    "Authorization": "bearer " + localStorage.getItem('token'),
    "Accept": "application/json",
    "cache-control": "no-cache"
  }
}).then(
  (response) => {
    // Handle data returned
    console.log(response.data);
  },
  //error callback
  (err) => console.log(err));
}

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

Having trouble incorporating this JavaScript code into customizing my material design chips

Having trouble integrating this code snippet into a React.js project. When I try to add it as a function, I get an error message saying that $ is not defined. I've experimented with different methods, but so far, I haven't been successful in gett ...

Utilizing Ajax to redirect users

Just finished creating a test Ajax call function in my script to add a basic layer of protection to my website. Here is the code: function testPHP() { $.ajax({ type: 'post', url: 'file.php', success: function() { al ...

I keep encountering a parser error when making an AJAX call to retrieve JSON data. It seems to be caused by

here is a snippet of code I am working on $.ajax({ type: 'GET', url: "<%=request.getContextPath()%>/manageUsers.do", cache: false, data:{ "resultType": "json", "submit": $.i18n.prop('esadmin.manage.users ...

Creating a Typescript project that compiles to UMD format, however, encountering the challenge of

I am trying to convert my index.ts file into a UMD index.js so that I can use it with a <script> tag. Here is the TypeScript configuration I am using: { "compilerOptions": { "outDir": "dist", "declaration& ...

Tips for formatting numerical output in EJS by rounding the value

I am displaying a value in EJS and I am looking to format it to show fewer decimal places. This is related to the EJS engine on the frontend. Value displayed: 4.333333333333333 I want it to be displayed like this: 4.3 The EJS code snippet used: <p cl ...

Using PHP to output a string within a JavaScript onclick function parameter

I am attempting to display a string in PHP as a string variable within a JavaScript function, but it is not appearing correctly. How can I resolve this issue? <?php $example1 = "example 1"; $example2 = "example 2"; $examp ...

Using Javascript, when the command key is pressed, open the link in a new window

Currently, I am working on a Javascript function that opens links in a new tab only when the "command" key is pressed on an Apple computer. Here is what I have so far: $(document).on('click','a[data-id]',function(e){ if(e.ctrlKey|| ...

Sending information from one ajax request to anotherORTransferring

Apologies for not including code in this post as I am currently working on a project in a car without internet access. Thankfully, I am using the amazing Stack Exchange app. Currently, I am facing a challenge where I need to work with two separate API cal ...

Identifying the moment when the hide() function in jQuery is triggered for an element

Is there a way to detect when the .hide() method in jQuery is triggered on an element? I attempted to attach an event listener to the hide event of that particular element: $('div').bind('hide', function(){ alert("Hidden&q ...

The binding style in vue.js using the ternary operator is throwing an error: Unexpected token ']'

partNav = Vue.component('part-nav', { data: navItems: [ { subItems: [ {...} {....} ] } {...} # another object in navItems array ] template: ' <div v-for="(navIte ...

The keyboard automatically disappeared upon clicking the select2 input

Whenever I select the select2 input, the keyboard automatically closes $('select').on('select2:open', function(e) { $('.select2-search input').prop('focus',false); }); Feel free to watch this video for more i ...

Steps to send an asynchronous AJAX request to the server-side within the JQuery validation plugin using the addMethod() function

Currently, I am in the process of developing my own framework using the JQuery validation plugin to validate CRUD forms both client-side and server-side. It is crucial that these forms are not static but rather created dynamically using "handlebar.js". Fo ...

Dealing with unassigned index in PHP and Ajax

What could be causing the variables in PHP to show as undefined? Code containing HTML <table> <tbody id="table"> <tr> <th colspan="2">SignUp</th> </tr> <tr> < ...

Struggling with setting up Vue.js

Having trouble installing Vuejs and encountering an error message: What mistake am I making and how can I successfully install it? Tried reinstalling Node.js and updating npm. C:\Users\chris>npm install -g @vue/cli C:\.node_modules&bso ...

How can I implement a toggle button to display additional details for a specific row within a table created using React.js?

I'm currently working on a project using Next.js and have come across an unexpected issue. Upon reading a JSON file, I populate a table with the data retrieved from it. Each piece of information in the table has hidden details that should only be reve ...

Material UI allows for the creation of numbered lists with ease. This

<List> {instructionList.map((el) => ( <ListItem divider key={el.id}> {el.type === 'number' ? <React.Fragmen ...

What is the best method for retrieving a JSON string that contains commas?

I have a JSON data with coordinates: "geometry":{"type":"Point","coordinates":[95.9174,3.8394,59]},"id":"us10002b0v" I am looking to extract each value in the coordinates array that is comma separated. In PHP, I would use extract(",",$geometry[coordinat ...

Ensure to verify the values of two variables when using a switch case statement

I'm working with two variables that can return true or false. My goal is to display a corresponding text message for each variable if it returns false. How can I effectively handle the ValidCheked and repeatChecked variables in a switch statement? ...

Creating functions within the $scope that do not directly access the $scope object

tag, I am looking to create a $scope function that specifically manipulates the variables it receives. To test this functionality, I have set up a Plunker available at http://plnkr.co/edit/BCo9aH?p=preview. In my setup, there is an ng-repeat loop that lis ...

Error: The terminal reports that the property 'then' cannot be found on the data type 'false' while trying to compile an Angular application

In my Angular application, which I initiate through the terminal with the command ng serve, I am encountering build errors that are showing in red on the terminal screen. ✔ Compiled successfully. ⠋ Generating browser application bundles... Error: s ...