[英]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.