Angular前端和JavaSpringBoot后端中被CORS策略阻止的请求?
创始人
2024-10-29 02:00:38
0

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数组中,以便在应用程序中使用。

相关内容

热门资讯

透视辅助!wepokerplu... 《透视辅助!wepokerplus外挂(透视)往昔是有挂(详细辅助透牌教程)》 wepokerplu...
透视规律(wePoKe)fis... 透视规律(wePoKe)fishpoker大菠萝外挂(透视)详细辅助科技教程是由北京得fishpok...
透视神器!hhpoker透视脚... 透视神器!hhpoker透视脚本视频(透视)详细辅助wpk教程(一贯真的是有挂)1、下载好hhpok...
透视教学!wepoker手机版... 透视教学!wepoker手机版透视脚本(透视)原来存在有挂(详细辅助第三方教程)准备好在wepoke...
透视app(wepOke)来玩... 透视app(wepOke)来玩app有挂吗(透视)详细辅助2025新版技巧1、许多玩家不知道来玩ap...
透视好友房!wpk辅助ai(透... 透视好友房!wpk辅助ai(透视)详细辅助黑科技教程(竟然真的有挂);1、不需要AI权限,帮助你快速...
透视游戏!hhpoker真的假... 透视游戏!hhpoker真的假的(透视)一贯存在有挂(详细辅助攻略教程)是一款可以让一直输的玩家,快...
透视透视挂(wePOke)im... 透视透视挂(wePOke)impoker有挂吗(透视)详细辅助2025新版1、不需要AI权限,帮助你...
透视软件!红龙poker辅助(... 透视软件!红龙poker辅助(透视)详细辅助软件教程(总是是有挂)红龙poker辅助辅助器中分为三种...
透视实锤!wepoker俱乐部... 透视实锤!wepoker俱乐部辅助(透视)素来是有挂(详细辅助新2025版);1.wepoker俱乐...