問題
我正在嘗試設定一個名為 Cookie 的標頭。我使用攔截器執行此操作,以便在每個請求上完成。
代碼
@Injectable
export class HeaderInterceptor implements HttpInterceptor {
constructor(private: authService: AuthenticationService) {}
intercept(reg: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return from(this.authService.getAuthentication()).pipe(
switchMap((token) => {
const headers = req.headers
.set(TOKEN, "someToken")
.set("Cookie", "someCookie")
.append("Content-Type", "application/json")
.append("Accept", "application/json");
const requestClone = req.clone({ headers, withCredentials: true });
return next.handle(requestClone);
})
);
}
}
怎么了
我總是得到:
設定禁止標頭的嘗試被拒絕:Cookie
那么我可以在這里做什么?我還嘗試withCredentials: true直接設定每個請求也不起作用。還有其他方法嗎?
uj5u.com熱心網友回復:
出于安全考慮并確保用戶代理保持對它們的完全控制,禁止以編程方式使用某些標頭。
Cookie是Forbidden 標頭名稱串列串列中的禁止標頭之一,因此您不能直接從代碼中將其設定在 HTTP 請求標頭中。
來自檔案:
禁止的標頭名稱是不能以編程方式修改的任何 HTTP 標頭的名稱;具體來說,一個 HTTP 請求標頭名稱
規范: https ://fetch.spec.whatwg.org/#forbidden-header-name
您可以隨時通過document.cookie設定 cookie ,瀏覽器會自動發送符合條件的 cookie。嘗試將 cookie 設定為外部域將被忽略。
Angular 提供了一個DOCUMENT DI 令牌,可用于在服務中注入檔案。您可以閱讀有關它的更多資訊how-to-inject-document-in-service。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/422467.html
標籤:
