1.确保后端响应头中设置了Access-Control-Expose-Headers字段,以允许这些自定义头信息被暴露。 2.在Angular中,使用withCredentials:true携带凭据,以便跨域请求中包含cookie或授权信息。 3.在拦截器中手动添加自定义响应头信息。
示例代码:
后端Node.js的设置:
const allowList = ["http://localhost:4200"];
const corsOptionsDelegate = function (req, callback) {
let corsOptions;
if (allowList.indexOf(req.header("Origin")) !== -1) {
corsOptions = { origin: true, exposedHeaders: ["Custom-Header"] };
} else {
corsOptions = { origin: false };
}
callback(null, corsOptions);
};
app.use(cors(corsOptionsDelegate));
在Angular中的http请求:
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer '+localStorage.getItem('token'),
'Custom-Header': 'custom value'
}),
withCredentials: true //携带cookie/授权信息
};
this.http.get('http://example.com/api/users', httpOptions).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
拦截器中手动添加响应头信息:
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const httpOptions = {
headers: req.headers.set('Custom-Header', 'custom value')
};
const newReq = req.clone(httpOptions);
return next.handle(newReq).pipe(
tap(event => {
if (event instanceof HttpResponse) {
event.headers.append('Custom-Header', 'custom value');
}
})
);
}