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... 透视教你"wepoker免费脚本咨询"一贯是真的辅助脚本(哔哩哔哩)1、很好的工具软件,可以解锁游戏...
透视揭露"aapok... 透视揭露"aapoker ai插件"竟然真的是有辅助器(哔哩哔哩)1、操作简单,无需aapoker ...
透视关于"aapok... 透视关于"aapoker透视怎么用"其实真的是有辅助神器(哔哩哔哩)1、aapoker透视怎么用免费...
透视了解"德普之星的... 透视了解"德普之星的辅助工具介绍"一直存在有辅助软件(哔哩哔哩)暗藏猫腻,小编详细说明德普之星的辅助...
透视解谜"wepok... 透视解谜"wepoker数据分析"果然真的是有辅助方法(哔哩哔哩)1、游戏颠覆性的策略玩法,独创攻略...
透视开挂"hhpko... 透视开挂"hhpkoer辅助器视频"切实是真的辅助攻略(哔哩哔哩)该软件可以轻松地帮助玩家将hhpk...
透视详细"wepok... 透视详细"wepoker究竟有没有透视"确实是有辅助app(哔哩哔哩)1、wepoker究竟有没有透...
透视解谜"we-po... 透视解谜"we-poker有人玩吗"确实是有辅助神器(哔哩哔哩)1、we-poker有人玩吗脚本辅助...
透视揭幕"红龙pok... 透视揭幕"红龙poker辅助平台"好像有辅助挂(哔哩哔哩)1、红龙poker辅助平台免费脚本咨询教程...
透视透视"wpk模拟... 透视透视"wpk模拟器多开"其实存在有辅助软件(哔哩哔哩)1、任何wpk模拟器多开透视是真的假的的玩...