如何删除HTTP拦截器中设置的内容类型以在angular4中上传文件

Har*_*n N 5 angular-http-interceptors angular

在我的应用程序中,我们设置content-type = application/json了拦截器。但是上传文件的内容类型应该是multipart/form-data,即contant-type = multipart/form-data当我们尝试上传表单数据时需要的内容。我的问题是,在发出发布请求以上传文件时,如何删除在拦截器中设置的内容类型。

谢谢,Harshavardhan

Vik*_*kas 12

删除现有标题

 if (!req.headers.has('Content-Type')) {
 req = req.clone({ headers: req.headers.delete('Content-Type','application/json') });
Run Code Online (Sandbox Code Playgroud)

添加新标题

req = req.clone({ headers: req.headers.set('Content-Type', 'multipart/form-data')})
Run Code Online (Sandbox Code Playgroud)

检查标头的当前值。

req.headers.get('Accept')
Run Code Online (Sandbox Code Playgroud)


and*_*wjs 5

我有一个类似的问题,最终通过在 body 上调用 toString() 来检查它是否是表单数据来解决它。

我确信有一种更简洁的方法来检查对象的类型,但这对我来说已经足够了:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let ignore =
        typeof req.body === "undefined"
        || req.body === null
        || req.body.toString() === "[object FormData]" // <-- This solves your problem
        || req.headers.has("Content-Type");

    if (ignore) {
        return next.handle(req);
    }

    const cloned = req.clone({
        headers: req.headers.set("Content-Type", 'application/json')
    });
    return next.handle(cloned);
}
Run Code Online (Sandbox Code Playgroud)

请注意,我也忽略了手动指定 Content-Type 的任何请求。