Home > Mobile >  FormData not working in Angular with Http Interceptor
FormData not working in Angular with Http Interceptor

Time:10-12

Hi I am trying to send http post formData to server with httpInterceptor with Bearer token. But the formData is not working.

const myheader = new HttpHeaders();
myheader.set('Content-Type', 'application/x-www-form-urlencoded');

const formData = new FormData();
formData.append('cart', 'hi');
formData.append('desc', this.cart.cartDesc);
formData.append('two', this.levelTwoData);
formData.append('main_cate', this.maincategory);
//formData.append('photo', this.imageData);

this.http.post<any>('http://localhost:8000/api/v1/cart/save/step1', formData, {
  headers: myheader
}).subscribe(response => {

});

If anyone have any Solution, please let me know. Thank you so much.

CodePudding user response:

I recommend you to use this package: angular-oauth2-oidc and try this:

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { RouterModule } from '@angular/router';

@NgModule({
    declarations: [AppComponent],
    imports: [
        BrowserModule,
        AppRoutingModule,
        HttpClientModule,
        RouterModule,
        OAuthModule.forRoot({
            resourceServer: {
                allowedUrls: ['https://localhost:5001', 'https://localhost:5443'],
                sendAccessToken: true,
            },
        }),
    ],
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: AuthInterceptor,
            multi: true,
        },
    ],
    bootstrap: [AppComponent],
})
export class AppModule {}

auth.interceptor.ts:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { OAuthService } from 'angular-oauth2-oidc';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(private oauthService: OAuthService) {}

    intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
        if (this.oauthService.hasValidAccessToken()) {
            const headers = request.headers.set('Authorization', `Bearer ${this.oauthService.getAccessToken()}`);
            const authenticatedRequest = request.clone({ headers });
            return next.handle(authenticatedRequest);
        }

        return next.handle(request);
    }
}

CodePudding user response:

I would start by looking at the Interceptor code, which you have not shared.

  • Related