简体   繁体   English

FormData 在 Angular 和 Http 拦截器中不起作用

[英]FormData not working in Angular with Http Interceptor

Hi I am trying to send http post formData to server with httpInterceptor with Bearer token.您好,我正在尝试使用带有 Bearer 令牌的 httpInterceptor 将 http post formData 发送到服务器。 But the formData is not working.但是 formData 不起作用。

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.太感谢了。

I recommend you to use this package: angular-oauth2-oidc and try this:我建议你使用这个 package: angular-oauth2-oidc试试这个:

app.module.ts:应用程序模块.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: 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);
    }
}

I would start by looking at the Interceptor code, which you have not shared.我将从查看您尚未共享的拦截器代码开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM