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.