简体   繁体   English

Django 和 Angular 文件上传中的 401“未经授权”错误

[英]401 "Unauthorized" error in Django and Angular File Upload

I have created a Django and Angular application to upload files.我创建了一个 Django 和 Angular 应用程序来上传文件。 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.我收到 401 - “未经授权”错误。 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:文件上传.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.这是因为我是使用签名拦截器并且我正在使用第三方 API 进行身份验证。 So instead of Django token, the third party APIs token was sent in header of POST request.因此,第三方 API 令牌不是 Django 令牌,而是在 POST 请求的 header 中发送的。

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).我使用 Httpbackend 处理对 Django DB 的 POST 请求,这样请求就不会被拦截,然后我添加了自定义 header (使用 Django 令牌)。 I used the code snippet on this website: https://levelup.gitconnected.com/the-correct-way-to-make-api-requests-in-an-angular-application-22a079fe8413我在这个网站上使用了代码片段: https://levelup.gitconnected.com/the-correct-way-to-make-api-requests-in-an-angular-application-22a079fe8413

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

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