Angular与Java后端返回CORS错误。
创始人
2024-10-30 18:30:12
0

解决Angular与Java后端返回CORS(跨域资源共享)错误的方法如下:

  1. 在Java后端代码中添加CORS配置: 在Java后端的接口方法上添加@CrossOrigin注解,允许指定的域名访问该接口。例如:
import org.springframework.web.bind.annotation.CrossOrigin;

@CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/api/data")
public ResponseEntity getData() {
   // 处理逻辑
}

在上面的示例中,我们允许来自"http://localhost:4200"域名的请求访问该接口。

  1. 在Angular应用的代码中添加CORS配置: 在Angular的服务文件中添加HTTP的头信息,以告诉服务器接受跨域请求。例如:
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class DataService {
  constructor(private http: HttpClient) { }
  
  getData() {
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
    return this.http.get('http://localhost:8080/api/data', { headers: headers });
  }
}

在上面的示例中,我们设置了"Content-Type"头信息,并将其发送到"http://localhost:8080/api/data"接口。

  1. 配置Java后端服务器的CORS: 如果你无法修改Java代码或无法使用@CrossOrigin注解,你可以在Java后端服务器的配置文件中添加CORS配置。以Spring Boot为例,你可以在application.properties或application.yml文件中添加如下配置: application.properties:
spring.mvc.dispatch-options-request=true
spring.web.cors.allowed-origins=http://localhost:4200
spring.web.cors.allowed-methods=GET,POST,PUT,DELETE
spring.web.cors.allowed-headers=Content-Type

application.yml:

spring:
  mvc:
    dispatch-options-request: true
  web:
    cors:
      allowed-origins: http://localhost:4200
      allowed-methods: GET,POST,PUT,DELETE
      allowed-headers: Content-Type

以上配置允许来自"http://localhost:4200"域名的请求访问Java后端,并允许GET、POST、PUT和DELETE方法。

请注意,这些解决方法仅提供了一种应对CORS错误的方式,具体的解决方法可能因你的应用程序和服务器配置而有所不同。

相关内容

热门资讯

透视苹果版!aapoker脚本... 透视苹果版!aapoker脚本(透视)发牌逻辑(竟然存在有挂)1、这是跨平台的aapoker脚本黑科...
透视游戏!aapoker透视脚... 透视游戏!aapoker透视脚本(透视)脚本(竟然是真的有挂)1、很好的工具软件,可以解锁游戏的aa...
透视线上!aapoker怎么开... 透视线上!aapoker怎么开辅助器(透视)辅助(都是是有挂)1、玩家可以在aapoker怎么开辅助...
透视中牌率!aapoker怎么... 透视中牌率!aapoker怎么选牌(透视)真的假的(果然存在有挂)1、实时aapoker怎么选牌开挂...
透视黑科技!aapoker免费... 透视黑科技!aapoker免费透视脚本(透视)透视脚本(竟然是真的有挂)1、点击下载安装,aapok...
辅助透视!aapoker怎么提... 辅助透视!aapoker怎么提高中牌率(透视)插件下载(本来真的是有挂)1、aapoker怎么提高中...
透视了解!aapoker辅助软... 透视了解!aapoker辅助软件合法吗(透视)脚本(原来真的是有挂)1、任何aapoker辅助软件合...
透视工具!aapoker辅助器... 透视工具!aapoker辅助器怎么用(透视)透视脚本入口(真是真的是有挂);1、aapoker辅助器...
透视app!aapoker辅助... 透视app!aapoker辅助怎么用(透视)辅助(一贯存在有挂)1、aapoker辅助怎么用系统规律...
透视辅助!aapoker俱乐部... 透视辅助!aapoker俱乐部靠谱吗(透视)插件(本来真的有挂)aapoker俱乐部靠谱吗辅助器中分...