Angular应用程序与部署在Docker容器中的SpringBootAPI之间的通信问题。
创始人
2024-10-30 14:30:24
0

如果您正在使用Docker部署Spring Boot API,可以按照以下步骤设置CORS(跨域资源共享)以解决此问题:

  1. 在Spring Boot API的应用程序配置文件application.properties或application.yml中添加以下代码:

application.properties

# CORS configuration
spring.mvc.cors.allowed-origins= http://localhost:4200
spring.mvc.cors.allowed-methods= GET, POST, PUT, DELETE, OPTIONS
spring.mvc.cors.allowed-headers= *

application.yml

# CORS configuration
spring:
  mvc:
    cors:
      allowed-origins: http://localhost:4200
      allowed-methods: GET, POST, PUT, DELETE, OPTIONS
      allowed-headers: "*"

修改allowed-origins以匹配您的Angular应用程序的基本URL。

  1. 在Angular应用程序的服务文件中添加以下HTTP头文件:
import { HttpHeaders } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Access-Control-Allow-Origin': 'http://localhost:8080',
    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
    'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
  })
};

将Access-Control-Allow-Origin和Access-Control-Allow-Headers的值更改为Spring Boot API运行的端口和请求的协议。

  1. 将httpOptions应用于HTTP请求。
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) { }
  getUsers() {
    return this.http.get('http://localhost:8080/api/users', httpOptions);
  }
}

使用上述步骤,您现在应该能够成功地通过Docker容器部署的Spring Boot API与Angular应用程序通信。

相关内容

热门资讯

安装程序教程!pokemmo脚... 安装程序教程!pokemmo脚本,七彩捞腌菜神器下载,透明挂教程(有挂透视)-哔哩哔哩七彩捞腌菜神器...
今日百科!wepoker买脚本... 今日百科!wepoker买脚本靠谱,雀姬无限钻石辅助,2025新版教程(有挂讲解)-哔哩哔哩1、玩家...
攻略讲解!cloudpoker... 攻略讲解!cloudpoker透视挂,xpoker辅助神器,必赢方法(有挂教程)-哔哩哔哩1、打开软...
玩家必备教程!购买wepoke... 玩家必备教程!购买wepoker模拟器,花花生活圈辅助器,专业教程(有挂功能)-哔哩哔哩该软件可以轻...
新手必备!wepoker轻量版... 新手必备!wepoker轻量版有透视,欢乐联盟游戏辅助,科技教程(有挂技术)-哔哩哔哩该软件可以轻松...
盘点一款!wpk透视挂,德普之... 盘点一款!wpk透视挂,德普之星有辅助软件,黑科技教程(有挂秘籍)-哔哩哔哩1、德普之星有辅助软件透...
我来教大家!破解辅助插件wep... 我来教大家!破解辅助插件wepoker,边锋嘉兴麻将辅助器,wepoke教程(存在有挂)-哔哩哔哩1...
关于!wepoker私人局俱乐... 关于!wepoker私人局俱乐部可以进,欢乐情怀开挂,德州教程(有挂细节)-哔哩哔哩1、wepoke...
必备攻略!德州之星扫描器,爱来... 必备攻略!德州之星扫描器,爱来掌中宝辅助器,wpk教程(有挂规律)-哔哩哔哩1、上手简单,内置详细流...
最新通报!pokemmo手机脚... 最新通报!pokemmo手机脚本辅助器,皮皮辅助软件下载,2025教程(有挂教程)-哔哩哔哩1、上手...