为了账号安全,请及时绑定邮箱和手机立即绑定

带有 Spring Boot 2 的 CORS

带有 Spring Boot 2 的 CORS

达令说 2022-07-14 10:14:01
我正在尝试将我的 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/这导致我得到以下代码:@Configurationpublic 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, …}一天来一直在为下一步要尝试什么而挠头,却什么也想不出来。建议?
查看完整描述

3 回答

?
翻阅古今

TA贡献1780条经验 获得超5个赞

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



查看完整回答
反对 回复 2022-07-14
?
茅侃侃

TA贡献1842条经验 获得超21个赞

在您的代码中添加此 WebSecurityConfigurerAdapter


import 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();

  }


}

还要添加以下 WebMvcConfigurer


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 WebMvcConfigurerImpl implements WebMvcConfigurer {


  @Override

  public void addCorsMappings(CorsRegistry registry) {

    registry.addMapping("/**");

  }

}

最后在你的休息控制器类的顶部添加这个注释:@CrossOrigin。


@CrossOrigin

public 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;


@Service

public 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);

  }


}


查看完整回答
反对 回复 2022-07-14
?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

@Configuration

public 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

@EnableWebMvc

public class WebConfig extends WebMvcConfigurerAdapter {


    @Override

    public void addCorsMappings(CorsRegistry registry) {

        registry.addMapping("/**");

    }

}

请在此处查看教程https://spring.io/blog/2015/06/08/cors-support-in-spring-framework


查看完整回答
反对 回复 2022-07-14
  • 3 回答
  • 0 关注
  • 129 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号