简体   繁体   中英

401 "Unauthorized" error in Django and Angular File Upload

I have created a Django and Angular application to upload files. It was working without errors until I integrated a login page. I have not been able to upload files since integration. I get 401 - "Unauthorized" error. What could have possibly gone wrong?

Auth-interceptor:

    import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest,HttpErrorResponse } from "@angular/common/http";
    import { Injectable } from "@angular/core";
    import { catchError, Observable, throwError } from "rxjs";
    import { LoginService } from "src/services/login.service";
    
    @Injectable()
    export class AuthInterceptorService implements HttpInterceptor {
      constructor(private authService: LoginService) {} 
     intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {  
        
    
        if (this.authService.isLoggedIn()) {
          const token = this.authService.getAuthToken();
          console.log("intercept",token)
         // If we have a token, we set it to the header
           request = request.clone({
            setHeaders: {Authorization: `Token ${token}`}
         });
      }
    
      return next.handle(request)
      }
      
    }
    

fileupload.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { LoginService } from 'src/services/login.service';
import { FileUploader, FileLikeObject } from 'ng2-file-upload';
import { concat, Observable } from  'rxjs';
import { HttpEvent, HttpEventType } from '@angular/common/http';

@Component({
  selector: 'app-fileupload',
  templateUrl: './fileupload.component.html',
  styleUrls: ['./fileupload.component.scss']
})
export class FileuploadComponent {

  DJANGO_SERVER = 'http://127.0.0.1:8081'
  public uploader: FileUploader = new FileUploader({});
  public hasBaseDropZoneOver: boolean = false;

  constructor(private formBuilder: FormBuilder, private uploadService: LoginService) { }

  fileOverBase(event):  void {
    this.hasBaseDropZoneOver  =  event;
}
getFiles(): FileLikeObject[] {
  return this.uploader.queue.map((fileItem) => {
    return fileItem.file;
  });
}
upload() {   
  let files = this.getFiles();
  console.log(files);
  let requests= [];
  files.forEach((file) => {
    let formData = new FormData();
    formData.append('file' , file.rawFile, file.name);
    requests.push(this.uploadService.upload(formData));   
    console.log(requests,file)
   
  });

  concat(...requests).subscribe(
    (res) => {
      
      console.log(res);
    },
    }
  );
  }}
   console.log(err);
    }
  );
  }}

service:

public upload(formData) {
    let token= localStorage.getItem('token');
    return this.http.post<any>(`${this.DJANGO_SERVER}/upload/`, formData).pipe(map((res) => {
      console.log(res)
       
     })
     )  
    
  }
    

Thank you

I resolved the issue. It was because I was usign interceptor and I was using third party API for authentication. So instead of Django token, the third party APIs token was sent in header of POST request.

How I resolved it? I used Httpbackend to process POST requests to Django DB so that the request is not intercepted and then I added custom header (with Django token to the reuest). I used the code snippet on this website: https://levelup.gitconnected.com/the-correct-way-to-make-api-requests-in-an-angular-application-22a079fe8413

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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