401 Unauthorized response returned upon making a POST request in Angular due to token invalidation

Looking for assistance on understanding and implementing the process of adding a product to the cart upon button click. I have a list of products retrieved from an API, each with options to increment quantity using + and - buttons. When the + button is clicked for the first time, I want the product to be added to the cart...

The goal is to trigger a POST request to my API upon clicking the + button, which will then add the selected product to the cart. Additionally, the API call should also verify and update the price if any changes have occurred.

I've created a cart.service file where I've included the following code, however, I keep encountering a 401 error (

{status: 401, message: "token_invalidate"}
message: "token_invalidate"
status: 401

) in the console upon button click... What am I doing wrong here?

cart.service.ts file:

  addUpdateProductToCart(quantity: number, produkt: Product) {
    return from(Preferences.get({ key: 'TOKEN_KEY' })).pipe(
      switchMap(token => {
        const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);
        // Initialize Params Object
        let params = new HttpParams();
        // Begin assigning parameters
        params = params.append('product', produkt.id);
        params = params.append('quantity', quantity);
        return this.httpClient.post(`${environment.apiUrl}cart`, { headers, observe: 'response' }, {params});
      }),
      catchError(err => {
        console.log(err.status);
        if (err.status === 400) {
          console.log(err.error.message);
        }
        if (err.status === 401) {
          // this.authService.logout();
          // this.router.navigateByUrl('/login', { replaceUrl: true });
        }
        return EMPTY;
      }),
    );
  };

And here's how I'm triggering the POST request on the page containing the product listings (subcategory.page.ts):

  incrementQty(index: number, produkt: Product) {
   
    const newQty = this.products[index].step += 1.00;

    this.cartService.addUpdateProductToCart(newQty, produkt).subscribe(
        data => {
          console.log(data);
        },
        error => {
          console.log('Error', error);
        }
        );
  }

HTML Code:

<ion-label>
  <div class="d-flex ion-justify-content-between">
     <div class="prod-details-wrapper">
                      <p class="product-id">{{ produkt.product_code }}</p>
                      <p class="product-em">EM: {{ produkt.unit }}</p>
                      <p class="product-packaging">Pakiranje: {{ produkt.min_weight }} {{ produkt.unit }}</p>
                    </div>
                    <div class="qty-input-wrapper">
                      <ion-item lines="none" slot="end">
                        <ion-icon color="vigros" name="remove-circle" (click)="decrementQty(i, produkt)"></ion-icon>
                        <ion-input type="number" value="0" min="0" step="1" [(ngModel)]="produkt.step"></ion-input>
                        <ion-icon color="vigros" name="add-circle" (click)="incrementQty(i, produkt)"></ion-icon>
                      </ion-item>
                    </div>
                  </div>
                </ion-label>

https://i.sstatic.net/rQ5OY.png

Answer №1

It is essential for a post to have some content, even if it's just an empty body.

In Visual Code, you can conveniently hover over Methods to understand the required parameters and their sequence. Don't disregard symbols like ! or ? after a parameter, simply input null or undefined if necessary.

-> Ensure your token insertion method is correct. Have you validated that your token is indeed valid?

If in doubt, try logging the token with console.log(token) and testing the request using tools like Postman or Swagger to troubleshoot any 401 errors.

If it's an API issue, take time to debug and identify where the Authorization process is failing.

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

Error in Vue: Trying to set a property ('message') on an undefined object

As a newcomer to Vue.js, there are some concepts that I may be overlooking. Despite working on it for months, I have been unable to find a solution. My goal is to change the message displayed in a v-alert by using a separate JavaScript script to import the ...

DOM doesn't reflect changes to nested object when component prop is updated

I have a complex object structured in a multidimensional way that appears as follows: obj: { 1: { 'a' => [ [] ], 'b' => [ [] ] }, 2: { 'x' => [ [], [] ] } } This object is located in the r ...

Struggling to Personalize Kendo Calendar Month templates using Knockout Kendo JS Binding

I have made modifications to the Kendo Calendar Month Template Resource which can be found Here without utilizing knockout-kendo.js. The official Kendo Reference is available Here. The issue arises when I implement the following code in knockout-kendo.js ...

How can you limit access to certain routes in Nuxt.js to only clients who possess a valid JWT token?

In Nuxt.js, implementing authentication can be done in the following steps: The client authenticates by sending its credentials in an HTTP request to a specific API route in the Nuxt backend; The Nuxt backend responds with a JWT token for accessing protec ...

Enhance the way UV coordinates are generated for rotated triangles/faces within THREE.js

While researching how to map a square texture onto n-sided polyhedrons using a convex hull generator in THREE.js, I found that existing solutions did not fully address my issue. The challenge was to ensure that the texture was not distorted and appeared co ...

Using HTML5 to overlay text on an image with a hyperlink

I'm interested in adding a hyperlink on top of an image using HTML5. Can you provide some guidance on how to achieve this? Regards, Ravi ...

Using useCallback with an arrow function as a prop argument

I'm having trouble understanding the code snippet below <Signup onClick={() => {}} /> Upon inspecting the Signup component, I noticed the implementation of useCallback as follows const Signup = ({onClick}) => { const handleClick = us ...

Is using $timeout still considered the most efficient method for waiting on an Angular directive template to load?

When it comes to waiting for a directive's template to render, our team has been following the approach of enclosing our DOM manipulation code in a $timeout within the directive's link function. This method was commonly used in the past, but I&ap ...

Saving asp.net strings in different formats to datetime fields in a database

Can someone please assist me with saving the string value of textbox to the database as a datetime, and for updating/editing purposes, display it again in the textbox as a string? The reason for this is that the datetime input will be copied from Outlook a ...

Show the GitHub repositories of the user within a React application

Even though I am relatively new to React, I managed to create a GitHub search application. In this app, you can input a user's name in a search box and view their avatar, bio, username, etc. However, I'm facing an issue with fetching their reposi ...

Halt the Bootstrap carousel while entering text in a textarea

Is it possible to achieve this? I think so. I have created a carousel with a form inside. The form includes a textarea and a submit button. Currently, the slider does not slide if the mouse pointer is inside it, which is good. However, if the pointer is o ...

Concealing a division element if there is no content inside of it

As a newcomer to jQuery, I am experimenting with setting up a code that hides a div when the 'innerHTML' is null. However, my attempt using the code below is not working. Can anyone point out where I might be going wrong? if (($("#php-errors").h ...

Change the websocket origin to localhost in a javascript setting

My server is hosting the domain example.com. Every time a user loads a page on this server, it utilizes a WebSocket client in JavaScript to connect to another WebSocket server. However, the other server has CORS enabled, which prevents the connection bec ...

The functionality of the disabler button is not fully operational on tablet devices

-I have a button: -I would like to use JavaScript to disable it: document.getElementById("input-datestart").disabled = true; -CSS: input:disabled { background-color: #fff!important; color: #000; } Text color [color: #000;] While it works on ...

Verify if a request attribute has been established using jQuery

How can I determine if an attribute is present in a request object? I have specific error scenarios where an error message needs to be sent to the client side: Here is the servlet code snippet: request.setAttribute("error", "The following term was not fo ...

Calculating different percentages from a reduced map containing JSON data

Forgive me in advance if there's a similar question out there, but after a day of searching, I couldn't find what I need. I'm calling an API that responds with data, and I've extracted the necessary details to create a JSON file with t ...

Is there a way to access the current $sce from a controller?

One way to access the current $scope outside of a controller is by using the following code: var $scope = angular.element('[ng-controller=ProductCtrl]').scope(); Is there a way to retrieve the $sce of the current controller? ...

What is the best way to identify the clicked cell?

I'm a JavaScript newbie trying to work with ExtJS 3.4. I've set up a basic tree with 3 columns and now I want to figure out which cell, row, or column has been selected. Currently, I'm following the example provided by Sencha at : var tr ...

What is the best method for converting Unix time to a readable date

<el-table-column label="Time Created" prop="create_time"></el-table-column> https://i.stack.imgur.com/aoLjf.png The timestamp data from the backend is in milliseconds format (e.g. 1527150668419) and is stored as create_time property in this.i ...

mention colleague(parent) instruction request

I have been exploring the use of metadata for setting HTML input attributes. After reading through the Attribute Directives Guide (https://angular.io/docs/ts/latest/guide/attribute-directives.html), I have developed the following implementation: import "r ...