Я использую серверную часть Node.JS, которая обычно принимает тип содержимого application/json
.Для одной конечной точки требуется файл, который необходимо отправить через форму multipart/form-data
.Этого можно достичь с помощью интерфейса FormData .
Поэтому перед отправкой данных из Angular на мой сервер я использовал интерфейс FormData
:
onSubmit() {
// ... some logic before
// Need to post multipart/form-data to our server, so let's create a FormData instance:
const formData = new FormData();
formData.append('icon', this.selectedIcon, this.selectedIcon.name); // the actual file
formData.append('name', this.createGroupForm.get('name').value); // other data from a Angular reactive form
// Send the FormData to the service
this.groupService.post(formData).subscribe((group) => {
console.log({
group,
});
});
}
Теперь с Angular HttpInterceptor
действительно легко определить, отправляете ли вы нормальные данные или FormData, и изменить заголовок content-type
на основе экземпляра request.body
:
export class ExampleInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
/**
* Let's assume that we need to set the contentType to application/json for every request.
*/
let contentType = 'application/json';
/**
* But when the data of the body is an instance of FormData, we can assume that we are uploading an file.
* Therefore, we need to change the contentType to multipart/form-data.
*/
if (request.body instanceof FormData) {
// we are sending a file here
contentType = 'multipart/form-data';
}
const clonedRequest= request.clone({
setHeaders: {
'content-type': contentType, // set the content-type here
},
});
return next.handle(clonedRequest);
}
}