[已解决]:从我的 Angular 应用程序向 Spring Boot API 网关发送 POST 请求且 CORS 配置正确时出现“未知错误”

问题描述 投票:0回答:1

当从我的 Angular 应用程序向我的 Spring Boot API 网关发送 POST 请求时,我收到“http://localhost:8080/api/user/auth/login: 0 Unknown Error”的 Http 失败响应。CORS 已配置正确,并且相同的请求在直接发送到用户服务时工作正常。API 网关日志不显示任何错误,浏览器控制台不提供额外的见解。有关如何解决此问题的任何建议吗?”。

API网关应用程序.properties

eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true
spring.application.name=api-gateway
eureka.client.service-url.defaultZone= http://localhost:8761/eureka
server.port=8080
## LOGS
logging.level.root=INFO
#class responsible for defining and identifying routes
logging.level.org.springframework.cloud.gateway.route.RouteDefinitionLocator = INFO
logging.level.org.springframework.cloud.gateway = TRACE
## END LOGS

## Routes
spring.cloud.gateway.routes[0].id=user-service
spring.cloud.gateway.routes[0].uri = lb://user-service
spring.cloud.gateway.routes[0].predicates[0]=Path=/api/user/**

控制台错误:

API GatewayCors 配置


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*") // Replace with your Angular application's URL
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("Content-Type", "Authorization");
    }
}


PS: 当我更改角度应用程序中的 URL 以直接向用户服务发送请求时,一切正常。

java angular spring-boot cors api-gateway
1个回答
1
投票

请在您的 api-gateway 中创建一个 application.yml 文件并将以下配置放入其中。

spring:
  application:
    name: gateway

  cloud:
    gateway:
      global-cors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods:
              - GET
              - POST
              - PUT
              - DELETE
              - PATCH
            allowedHeaders:
              - "Origin"
              - "Content-Type"
              - "Accept"
              - "Authorization"
              - "User-Key"
              - "Request-Tracker"
              - "Session-Tracker"
              - "X-XSRF-TOKEN"
              - "X-IBM-CLIENT-ID"
              - "Message-ID"
              - "X-IBM-CLIENT-SECRET"
      default-filters:
        - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin, RETAIN_FIRST

© www.soinside.com 2019 - 2024. All rights reserved.