首页 > 解决方案 > Angular HttpPost 方法返回为 405 方法不允许

问题描述

Angular HttpPost 方法返回为不允许的 405 方法。

服务电话:

private fileUploadUrl = 'file-tranfer/uploadFile';

formHtppOptions(params): any {
    const httpOptions = {
      headers: {'Content-Type': 'application/json', 'Application-Token': this.getToken()},
      params: params,
             };
    return httpOptions;
  }

getBaseUrl(): string {
     return this.sharedSessionService.sharingData.config.uiService.url;
  }

  getToken(): string {
    return this.sharedSessionService.sharingData.config.uiService.token;
  }

  postFileTransferUpload(formData):  Observable<object> {
    const baseUrl = this.getBaseUrl();
    return this.http.post<Object>(baseUrl + this.fileUploadUrl, formData, this.formHtppOptions({}));
  }

控制器:

uploadFile() {
  const formData = new FormData();
  formData.set('file', this.fileToUpload);
   formData.set('company', this.selectedCompany);
  formData.set('fileId', this.selectedFileType);

   this.iportalUploadService.postFileTransferUpload(formData)
  .subscribe(data => {
    debugger;
  });
}

错误:上传时的控制台错误

标签: angularhttpangular5angular2-services

解决方案


Content-Type: 'application/json当数据为 时,代码错误地设置new FormData()

你根本不需要Content-Type

formHtppOptions(params): any {
    const httpOptions = {
      headers: { ̶'̶C̶o̶n̶t̶e̶n̶t̶-̶T̶y̶p̶e̶'̶:̶ ̶'̶a̶p̶p̶l̶i̶c̶a̶t̶i̶o̶n̶/̶j̶s̶o̶n̶'̶,̶
                 'Application-Token': this.getToken()
      },
      params: params,
    };
    return httpOptions;
}

当使用FormData 对象作为数据调用XHR.send 方法时,它会自动将内容类型设置为并附加正确的部分边界。"multipart/form-data"


推荐阅读