猿问

带有 Spring Boot 2 的 CORS

我正在尝试将我的 Angular 应用程序连接到我的新 Spring Boot 2 控制器。我开始一切,我得到:


Access to XMLHttpRequest at 'localhost:8093/restapi/setup' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

其次是:


ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "localhost:8093/restapi/setup", ok: false, …}

所以这是CORS,对吧?正如你所料,当我localhost:8093/restapi/setup从邮递员那里打来时,我得到了有效的回应。


所以我做了一些研究,特别是我发现:No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API


我终于在这里找到了这篇文章:


https://chariotsolutions.com/blog/post/angular-2-spring-boot-jwt-cors_part1/


这导致我得到以下代码:


@Configuration

public class ManageConfiguration {

    private static final Logger         LOGGER = LogManager.getLogger(ManageConfiguration.class);


    @Bean

    public CorsFilter corsFilter() {

        LOGGER.debug("Configuring CORS");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration config = new CorsConfiguration();

        config.setAllowCredentials(true);

        config.addAllowedOrigin("*");

        config.addAllowedHeader("*");

        config.addAllowedMethod("OPTIONS");

        config.addAllowedMethod("GET");

        config.addAllowedMethod("POST");

        config.addAllowedMethod("PUT");

        config.addAllowedMethod("DELETE");

        source.registerCorsConfiguration("/**", config);

        return new CorsFilter(source);

    }

}

所以我认为这很简单,现在再试一次,我得到:


Access to XMLHttpRequest at 'localhost:8093/restapi/setup' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

其次是:


ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "localhost:8093/restapi/setup", ok: false, …}


一天来一直在为下一步要尝试什么而挠头,却什么也想不出来。建议?


达令说
浏览 130回答 3
3回答

翻阅古今

我认为您http://在请求 URL 中发送没有协议前缀的 ajax 请求,请尝试http://localhost:8093/restapi/setup从 ajax 中点击。

茅侃侃

在您的代码中添加此 WebSecurityConfigurerAdapterimport org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@EnableWebSecurity@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {  @Override  protected void configure(HttpSecurity http) throws Exception {    http.cors().and().csrf().disable();  }}还要添加以下 WebMvcConfigurerimport org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configurationpublic class WebMvcConfigurerImpl implements WebMvcConfigurer {  @Override  public void addCorsMappings(CorsRegistry registry) {    registry.addMapping("/**");  }}最后在你的休息控制器类的顶部添加这个注释:@CrossOrigin。@CrossOriginpublic class RestController {// Your methods}如果你有过滤器,你可以在响应中添加以下属性,如果你没有,你可以使用这个。import java.io.IOException;import javax.servlet.FilterChain;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Service;import org.springframework.web.filter.OncePerRequestFilter;@Servicepublic class JwtAuthenticationFilter extends OncePerRequestFilter {  @Override  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {    response.setHeader("Access-Control-Allow-Origin", "*");    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");    response.setHeader("Access-Control-Allow-Credentials", "true");    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");    response.setHeader("Access-Control-Expose-Headers", "Content-Length, Authorization");    filterChain.doFilter(request, response);  }}

慕尼黑的夜晚无繁华

@Configurationpublic class CorsConfig {    @Bean    public WebMvcConfigurer corsConfigurer() {        return new WebMvcConfigurerAdapter() {            @Override            public void addCorsMappings(CorsRegistry registry) {                registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")                        .allowedHeaders("*");            }        };    }}@Configuration@EnableWebMvcpublic class WebConfig extends WebMvcConfigurerAdapter {    @Override    public void addCorsMappings(CorsRegistry registry) {        registry.addMapping("/**");    }}请在此处查看教程https://spring.io/blog/2015/06/08/cors-support-in-spring-framework
随时随地看视频慕课网APP

相关分类

Java
我要回答