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

相关内容

热门资讯

透视总结!wpk免费辅助(透视... 透视总结!wpk免费辅助(透视)一直有挂(详细辅助AI教程)1、玩家可以在软件透明挂俱乐部对游戏的模...
透视插件!pokermaste... 透视插件!pokermaster修改器(透视)原来真的是有挂(详细辅助透牌教程)1、透视辅助简单,软...
透视神器!wepoker轻量版... 透视神器!wepoker轻量版透视(透视)其实是有挂(详细辅助透牌教程)1、玩家可以在软件透明挂俱乐...
透视黑科技!wepokerh5... 透视黑科技!wepokerh5破解(透视)切实是真的有挂(详细辅助爆料教程)1、系统规律教程、辅助透...
透视app!wepoker免费... 透视app!wepoker免费钻石(透视)果然真的有挂(详细辅助插件教程);1)辅助挂:进一步探索辅...
透视游戏!aapoker辅助软... 透视游戏!aapoker辅助软件合法吗(透视)原来存在有挂(详细辅助解密教程)小薇(透视辅助)致您一...
透视app!wejoker辅助... 透视app!wejoker辅助脚本(透视)切实存在有挂(详细辅助安装教程);1、透视app!wejo...
透视私人局!hhpoker可以... 透视私人局!hhpoker可以开挂吗(透视)切实真的是有挂(详细辅助透明挂教程);暗藏猫腻,小编详细...
透视黑科技!wepoker亲友... 透视黑科技!wepoker亲友圈有用吗(透视)好像真的有挂(详细辅助细节揭秘);1、打开软件启动之后...
透视免费!德普之星app安卓版... 透视免费!德普之星app安卓版破解版(透视)其实有挂(详细辅助新版2025教程)1、金币登录送、破产...