menu

Questions & Answers

POST request in angular returning 401 token invalidate

I need help with understanding and implementing how to add a product to my cart when clicking a button. In my example I have a list of products that I get from an API and each product has a + and - button to increase its quantity and on first click on + button to add it to cart...

I want to achieve that on the click of + button a post request happens to my API that then adds this product to my cart. My API call also check and updates the price if there has been a price change.

Now I have created a cart.service file where I added the bellow code but I keep getting a 401 error (

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

) in console on button click... What is my mistake 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 this is how I'm triggering this POST request in the page where the products are listed (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);
        }
        );
  }

And the 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>

Sample of a listed product with + and - button

Comments:
2023-01-17 18:42:14
The post request expects a body in the second position. this.httpClient.post(url, body, options). If there is no body to pass, then pass null. Take a look to the official documentation.
2023-01-17 18:42:14
Im verry new to Angular... could you provide an example please?... I dont understand what I have to pass as body
2023-01-17 18:42:14
Change the line return this.httpClient.post(environment.apiUrl + 'cart', { headers, observe: 'response' }, {params}); to return this.httpClient.post(environment.apiUrl + 'cart', null, { headers, observe: 'response', params });. Your template string ${environment.apiUrl}cart is perfectly fine, i just changed it for formatting purposes.
2023-01-17 18:42:14
This seems to work :) but now I'm getting error 400 that says I have to add quantity... even tho the quantity sent is 1
2023-01-17 18:42:14
Try just to append the params and not to reassign them like this: // Begin assigning parameters params.append('product', produkt.id); params.append('quantity', quantity); and check the request url in the browser devtool.
2023-01-17 18:42:15
@riorudo Now the response is please select a prodct
2023-01-17 18:42:15
could the be an issue with the code in the file subcategory.page.ts in the incrementQty function?
2023-01-17 18:42:15
Answers(1) :

Post needs a body doesn't matter if its empty or not.

if you use Visual Code you can hover over Methods to see what parameters are necessary and in what order. ! or ? after a Parameter doesnt mean you can just skip it just put it down as null or undefined.

-> post(url, body, headers, params)

The way you add your token should work. Are you 100% sure you have a valid token?

If not put console.log(token) after you receive it and try the request with postman/swagger and see if you still get a 401 error.

Also if its your API just debug it and find out at what point the Authorization fails.

Comments:
2023-01-17 18:42:15
Yes the token is valid... the same function works with get method for getting categories and products...
2023-01-17 18:42:15
Then swap your body and header like @riorudo suggested then everything should work, also you don't have to use "{params}" just use "params"
2023-01-17 18:42:15
If you use visual code you can usually hover over functions and see what parameters are necessary and in what order.
2023-01-17 18:42:15
how do I add data to body?
2023-01-17 18:42:15
You can pass anything if its a login {username, password} works or you can initialize an object let obj = {username, password} and pass obj as the body.