gpt4 book ai didi

java - Google Cloud 请求的资源上不存在 'Access-Control-Allow-Origin' header

转载 作者:行者123 更新时间:2023-11-30 02:02:09 24 4
gpt4 key购买 nike

我创建了一个 REST API 并将其上传到 Google Cloud。当我尝试从另一个域访问时,出现以下错误:

跨源请求被阻止:同源策略不允许读取 http://35.198.15.248:8080/api/clientes/pf/ 处的远程资源。 (原因:CORS请求未成功)。

然后我添加了以下类:

@Configuration
@EnableWebMvc

public class ConfiguracaoDeCors extends WebMvcConfigurerAdapter {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST, GET, HEAD, DELETE, UPDATE")
.allowedHeaders("Content-Type", "Authorization")
.allowCredentials(false)
.maxAge(32400);
}
}

错误仍然存​​在。有人可以帮忙吗?

添加:

它的工作

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers(PUBLICOS).permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}

最佳答案

使用 spring 提供的 CrossOrigin 注释可能对您的情况有所帮助:

import org.springframework.web.bind.annotation.CrossOrigin;

@CrossOrigin(origins = "http://localhost:9000")
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}

如果您通过 GlobalConfiguration 进行配置,下面的代码片段可能也会有所帮助。

@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
}
};
}

关于java - Google Cloud 请求的资源上不存在 'Access-Control-Allow-Origin' header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52500327/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com