1.在Spring Boot后端的控制器类中添加@CrossOrigin
注解。
如下所示:
@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class MyController {
...
}
其中,origins
参数指定了允许的源,可以是域名或IP地址。此参数是可选的,也可以设置为通配符*
,表示允许来自任何源的请求。
2.在Angular前端的请求配置中添加withCredentials: true
选项。
如下所示:
import { HttpClient } from '@angular/common/http';
@Injectable()
export class MyService {
private url = 'http://localhost:8080/some-endpoint';
constructor(private http: HttpClient) {}
getData() {
const options = { withCredentials: true };
return this.http.get(this.url, options);
}
}
这里withCredentials
选项指定了是否在请求中发送凭证(如cookie)。
需要注意的是,如果在Angular前端中使用了HttpInterceptor
拦截器,则可能需要在拦截器中手动添加withCredentials
选项,如下所示:
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
@Injectable()
export class MyInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler) {
const authReq = req.clone({ withCredentials: true });
return next.handle(authReq);
}
}
这里拦截器使用clone()
方法创建了一个新的请求,并将withCredentials
选项添加到了该请求中。需要将拦截器添加到providers
数组中,以便在应用程序中使用。