部署到 Google App Engine 时 Spring Boot CORS 配置不起作用

Posted

技术标签:

【中文标题】部署到 Google App Engine 时 Spring Boot CORS 配置不起作用【英文标题】:Spring Boot CORS Configuration not working when deployed to Google App Engine 【发布时间】:2021-05-24 00:49:03 【问题描述】:

我有 2 个 GAE,一个是 Spring Boot 后端,另一个是 Vue.js 前端。当我在本地测试它时,CORS 配置工作正常,但是当我部署到 GAE 时,我得到以下响应:

Access to fetch at BACKEND/function from origin FRONTEND has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我的 Spring Security CORS 配置如下所示:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter 

    @Override
    protected void configure(HttpSecurity security) throws Exception 
        security.cors().and().csrf().disable().httpBasic().disable();
    

    @Bean
    CorsConfigurationSource corsConfigurationSource() 
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList(frontend-url));
        configuration.setAllowedMethods(Arrays.asList("POST"));
        configuration.setAllowedHeaders(Arrays.asList("*")); 
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    

我已经坚持了将近一天,现在任何帮助都将不胜感激。如果您需要更多信息,请告诉我。

【问题讨论】:

【参考方案1】:

尝试设置allowed headers并考虑configuration.setExposedHeaders

configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Origin", "Origin"));

也许您需要将GET 添加到allowed methods

configuration.setAllowedMethods(Arrays.asList("GET", "POST"));

【讨论】:

以上是关于部署到 Google App Engine 时 Spring Boot CORS 配置不起作用的主要内容,如果未能解决你的问题,请参考以下文章

部署到 Google App Engine 时 Spring Boot CORS 配置不起作用

将 Meteor 部署到 Google App Engine 2017

java.lang.NoClassDefFoundError:部署到Google App Engine时无法初始化类net.sf.cglib.proxy.Enhancer。

Google App Engine检查更新

Google App Engine Java - 对于 POST 参数,request.getParameter 在部署时返回 null,但在本地工作

如何将新服务部署到 Google App Engine 中的现有应用程序?