简体   繁体   English

如何在 Angular 中自动检测内容类型

[英]How to detect content-type automatically in Angular

In my Angular 9 application I am trying to automatically set the content-type for every different HTTP request I do.在我的 Angular 9 应用程序中,我试图为我所做的每个不同的 HTTP 请求自动设置内容类型。

In Angular doc I found this detectContentTypeHeader method but it seems not working good.Angular 文档中,我发现了这个detectContentTypeHeader方法,但似乎效果不佳。 In my case for example for this type of body:以我为例,对于这种类型的身体:

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

it detects text/plain instead of application/json but the body is a correct JSON, so am I wrong something?它检测text/plain而不是application/json ,但正文是正确的 JSON,所以我错了吗? Is there a way to do it automatically or I need to set it for every request?有没有办法自动完成,或者我需要为每个请求设置它? (I am already using an interceptor) (我已经在使用拦截器了)

multipart/form-data多部分/表单数据

If you pass in an object instead of a string as the request body it will detect it as application/json .如果您传入object而不是string作为请求正文,它将检测为application/json

The reason it's detecting a string as text/plain is written in the source code将字符串检测为text/plain的原因写在源代码

Technically, strings could be a form of JSON data, but it's safe enough to assume they're plain strings从技术上讲,字符串可能是 JSON 数据的一种形式,但假设它们是纯字符串是足够安全的

If for some reason you still want to detect a string as a valid JSON you can do the following:如果由于某种原因您仍想将字符串检测为有效的 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) });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何告诉Angular 2停止自动设置Content-Type标头? - How can I tell Angular 2 to stop setting Content-Type headers automatically? 如何在 Angular 拦截器中为“Content-Type”header 设置 null 值? - How to set a null value for “Content-Type” header in Angular interceptor? 如何更改Angular5的内容类型-HTTP RequestOptions HEADERS - How to Change the Content-Type of Angular5 - HTTP RequestOptions HEADERS 在Angular 6中更改某些请求的Content-Type - Change Content-Type for certain requests in Angular 6 如何设置内容类型和接受角度2获取错误415不支持的媒体类型 - How to set Content-Type and Accept in angular2 getting error 415 Unsupported Media Type 如何在Angular2中发布而不设置内容类型(或如何发布到Zapier Webhook) - How to POST in Angular2 without setting content-type (or how to post to Zapier Webhook) Angular 如何检查 HttpRequest 对象以设置正确的标题内容类型? - Angular How to check HttpRequest object to set proper content-type for headers? 无法在Angular FileUpload控件中设置Content-Type - Cannot set Content-Type in Angular FileUpload control Angular 2,Http和Not设置Content-Type“application / json” - Angular 2, Http and Not setting Content-Type “application/json” Angular不发送内容类型请求标头 - Angular Don't Send Content-Type Request Header
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM