[英]How can I tell Angular 2 to stop setting Content-Type headers automatically?
[英]How to detect content-type automatically in Angular
在我的 Angular 9 應用程序中,我試圖為我所做的每個不同的 HTTP 請求自動設置內容類型。
在Angular 文檔中,我發現了這個detectContentTypeHeader
方法,但似乎效果不佳。 以我為例,對於這種類型的身體:
{"username":"admin","password":"pwd","tenant":"12345"}
它檢測text/plain
而不是application/json
,但正文是正確的 JSON,所以我錯了嗎? 有沒有辦法自動完成,或者我需要為每個請求設置它? (我已經在使用攔截器了)
多部分/表單數據
如果您傳入object
而不是string
作為請求正文,它將檢測為application/json
。
將字符串檢測為text/plain
的原因寫在源代碼中
從技術上講,字符串可能是 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) });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.