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应用程序通信。

相关内容

热门资讯

透视学习!aapoker辅助插... 透视学习!aapoker辅助插件工具,AApoker辅助切实是有教程,2分钟教程(有挂解密)1、aa...
据公告内容!wepoker私人... 据公告内容!wepoker私人局透视教程,微信小程序微乐辅助器苹果,教你透视(有挂教程)-哔哩哔哩1...
透视总结!wepokerplu... 透视总结!wepokerplus外g挂,wepoker透视脚本免费app(透视)一贯是真的教程(哔哩...
现就发布提示!wejoker透... 现就发布提示!wejoker透视方法,微乐河北自建房脚本免费入口,辅助透视(有挂技巧)-哔哩哔哩1)...
透视透视挂!wepoker有没... 透视透视挂!wepoker有没有透视方法,微乐广西小程序开发,分享透视(有挂存在)-哔哩哔哩1、we...
透视必备!hhpoker底牌透... 透视必备!hhpoker底牌透视脚本,hhpoker真的假的(透视)确实是真的app(哔哩哔哩)1、...
透视透视挂!wepoker怎么... 透视透视挂!wepoker怎么开辅助,微乐陕西小程序脚本,辅助脚本(有挂攻略)-哔哩哔哩1、wepo...
透视曝光!wepoker透视苹... 透视曝光!wepoker透视苹果系统,wepoker有辅助功能吗(透视)其实有挂(哔哩哔哩)进入游戏...
透视攻略!aapoker脚本,... 透视攻略!aapoker脚本,AApoker辅助插件竟然有神器,第八分钟教程(有挂分析)1、许多玩家...
透视窍要!德普之星辅助器怎么用... 透视窍要!德普之星辅助器怎么用,德普辅助器一贯有神器,第3分钟教程(有挂方法)1、超多福利:超高返利...