简体   繁体   中英

Angular HttpPost method returns as 405 method not allowed

Angular HttpPost method returns as 405 method not allowed.

service call:

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({}));
  }

Controller:

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;
  });
}

error : console error on upload

Code erroneously sets Content-Type: 'application/json when the data is new FormData() .

You don't need Content-Type at all:

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;
}

When the XHR.send method is invoked with a FormData object as data, it automatically sets the content type to "multipart/form-data" and appends the proper part boundary.

Looks like, server to which you are sending the Post request(your Site's server) has been configured to block Post request. Please configure your server to allow the Post request. Its back-end issue I guess

Please follow below documentation

http://www.checkupdown.com/status/E405.html

As @georgeawg mentioned, you don't need to assign the content-type here, as its unnecessary because the data here is FormData(). So all you need to do is to remove this part

'Content-Type': 'application/json'

from the headers. Also make sure that you include Access-Control-Allow-Methods: POST in your headers if possible (only if the above mentioned solution doesnot works fine) as it might be the case that your POST request gets blocked on the browser side as its not allowed.

Hope it works totally fine now !

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