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

相关内容

热门资讯

透视实锤"wepok... 1、透视实锤"wepoker私人局透视"详细辅助2025教程(私人局辅助器可以用方法)2、进入游戏-...
透视辅助"来玩app... 自定义来玩app 德州 辅助系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器...
透视苹果版"werp... 透视苹果版"werplan辅助软件"详细辅助玩家教你(私局辅助辅助);支持2-10人实时对战,虚拟庄...
透视计算"we-po... 透视计算"we-poker靠谱吗"详细辅助技巧教程(辅助脚本辅助);支持2-10人实时对战,虚拟庄家...
透视ai"aapok... 透视ai"aapoker安装包怎么使用"详细辅助解密教程(可以透视码方法);《WPK辅助透视》‌:支...
透视总结"hhpok... 透视总结"hhpoker底牌透视脚本"详细辅助详细教程(透视有透明);实战中需综合运用上述技巧,并根...
透视总结"wepok... 自定义wepoker高级辅助系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器...
透视规律"wepok... 透视规律"wepoker有辅助功能吗"详细辅助扑克教程(私人局透视方法软件);致您一封信;亲爱wep...
透视插件"wpk透视... 透视插件"wpk透视辅助下载"详细辅助细节揭秘(透视脚本安卓辅助)1、很好的工具软件,可以解锁游戏的...
透视辅助"hhpok... 透视辅助"hhpoker智能辅助插件"详细辅助辅助教程(私人局辅助器可以用透明);小薇(透视辅助)致...