在Angular 11中,可以通过设置withCredentials
属性来发送Cookie。默认情况下,withCredentials
属性是false,这意味着在请求中不会发送Cookie。要发送Cookie,你需要将withCredentials
属性设置为true。
以下是一个示例,演示如何在Angular 11中发送Cookie:
HttpClient
和HttpHeaders
:import { HttpClient, HttpHeaders } from '@angular/common/http';
HttpClient
:constructor(private http: HttpClient) { }
withCredentials
为true:const url = 'https://example.com/api/endpoint';
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
withCredentials: true
};
this.http.get(url, options)
.subscribe(response => {
console.log(response);
}, error => {
console.error(error);
});
在上述示例中,我们使用HttpClient
的get
方法发送一个GET请求,并将withCredentials
属性设置为true。这将确保在请求中发送Cookie。
请确保将示例中的URL替换为你自己的API端点URL,并根据需要调整请求方法(例如POST、PUT等)和请求头(例如Content-Type)。
通过这种方式,你可以在Angular 11中发送带有Cookie的请求。