【问题标题】:How to detect content-type automatically in Angular如何在 Angular 中自动检测内容类型
【发布时间】:2020-04-16 18:46:52
【问题描述】:

在我的 Angular 9 应用程序中,我尝试为我所做的每个不同的 HTTP 请求自动设置内容类型。

Angular doc 我发现了这个detectContentTypeHeader 方法,但它似乎效果不佳。 以我为例,对于这种类型的身体:

{"username":"admin","password":"pwd","tenant":"12345"}

它检测到 text/plain 而不是 application/json 但正文是正确的 JSON,所以我错了吗? 有没有办法自动完成,或者我需要为每个请求设置它? (我已经在使用拦截器了)

多部分/表单数据

【问题讨论】:

    标签: angular


    【解决方案1】:

    如果您传入 object 而不是 string 作为请求正文,它将检测为 application/json

    将字符串检测为text/plain 的原因写在source code

    从技术上讲,字符串可以是 JSON 数据的一种形式,但假设它们是纯字符串就足够安全了

    如果由于某种原因您仍想将字符串检测为有效的 JSON,您可以执行以下操作:

    let contentType = req.detectContentTypeHeader();
    
    if (typeof req.body === 'string') {
      try {
        JSON.parse(req.body);
        contentType = 'application/json';
      } catch {}
    }
    
    req = req.clone({ headers: req.headers.set('content-type', contentType) });
    

    【讨论】:

    • 对不起,这个身体不是一个物体吗? {"username":"admin","password":"pwd"}
    • @AlessandroCeleghin 这很难说,你应该做一个 typeof 值并将其记录在控制台中,它很可能是对象的字符串化版本,否则 Angular 不会将其检测为text/plain.
    • 你真的不应该设置内容类型。 Angular 非常适合为您确定正确的。你想解决什么问题?
    • 是的,可能最好不要手动设置 contentType。所以我需要更新我的一些身体,让它自动工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    • 2012-03-11
    相关资源
    最近更新 更多