4 回答
TA贡献1788条经验 获得超4个赞
尝试在 Spring REST 端点上使用注释“@CrossOrigin”,位于“@RequestMapping”注释上方。
例如:-
@CrossOrigin @RequestMapping(value="/login",method=RequestMethod.POST)
TA贡献1777条经验 获得超3个赞
当请求 POST 时,您可能需要额外的配置,如下所示;
axio({
method: 'put',
headers: {
'Content-Type': 'application/json',
},
data: JSON.stringify({
"username": "username",
"password": "password"
}),
});
TA贡献1725条经验 获得超7个赞
请将以下文件添加到您的项目中存在 Main spring boot 类的包中。这对我来说适用于 Spring boot、React 生态系统中的所有 CORS 问题。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class CorsWebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
registry.addMapping("/*.html");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/api/v2/api-docs", "/v2/api-docs");
registry.addRedirectViewController("/api/swagger-resources/configuration/ui",
"/swagger-resources/configuration/ui");
registry.addRedirectViewController("/api/swagger-resources/configuration/security",
"/swagger-resources/configuration/security");
registry.addRedirectViewController("/api/swagger-resources", "/swagger-resources");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui.html**")
.addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
registry.addResourceHandler("/api/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}}
TA贡献1820条经验 获得超2个赞
在u配置中创建这个bean
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(ImmutableList.of(
"http://example.net",
"http://example.com",
));
configuration.setAllowedMethods(ImmutableList.of("HEAD", "OPTIONS", "GET", "POST", "PUT", "DELETE", "PATCH"));
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(ImmutableList.of("*"));
configuration.setExposedHeaders(ImmutableList.of("Content-Disposition"));
configuration.setMaxAge(3600L);
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
添加回答
举报