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、不需要AI权限,帮助你快速的进...
透视解迷"hhpok... 透视解迷"hhpoker是内部控制吗"本来真的有辅助脚本(哔哩哔哩)1、透视解迷"hhpoker是内...
透视教你"xpoke... 透视教你"xpoker辅助工具"都是存在有辅助软件(哔哩哔哩)1、透视教你"xpoker辅助工具"都...
透视教你"hhpok... 透视教你"hhpoker有后台操作吗"确实真的是有辅助神器(哔哩哔哩)1、用户打开应用后不用登录就可...
透视推荐"wpk作必... 透视推荐"wpk作必弊是真的吗"切实真的是有辅助工具(哔哩哔哩)1、很好的工具软件,可以解锁游戏的w...
透视关于"德州局透视... 透视关于"德州局透视"真是存在有辅助脚本(哔哩哔哩)1、进入游戏-大厅左侧-新手福利-激活码辅助透视...
透视辅助"wepok... 透视辅助"wepoker养号规律"都是存在有辅助教程(哔哩哔哩)1、首先打开wepoker养号规律辅...
透视总结"wepok... 透视总结"wepoker私人局怎么玩"都是真的有辅助方法(哔哩哔哩)wepoker私人局怎么玩辅助器...
透视解密"hhpok... 透视解密"hhpoker辅助"切实是有辅助脚本(哔哩哔哩)1、这是跨平台的hhpoker辅助轻量版有...
透视揭幕"wepok... 透视揭幕"wepoker游戏下载"一贯是有辅助器(哔哩哔哩);1、实时wepoker游戏下载透视辅助...