CORS 问题 - 对预检请求的响应未通过访问控制检查:

我正在研究 reactjs 前端,在后端使用 spring boot。我正在尝试从前端调用端点,如下所示:


testOktaTokenAtRest(data) {

  var oauth=JSON.parse(localStorage.getItem('okta-token-storage'))

  console.log("toekn is: ==>  "+oauth.accessToken.tokenType + 

  oauth.accessToken.accessToken)

  console.log("toekn received from action is inside this obj: ",data)

  var searchCriteria = JSON.stringify(data.data)

  console.log("searchCriteria data -------: " , searchCriteria)


 let _headerForSearch={

    auth : 'Bearer ' + oauth.accessToken.accessToken 

  }

  $.ajax({

    method: "post",

    url: "http://localhost:8000/ckcapp/api/posttest",

    contentType: "application/json",

    dataType: "json",

    data:searchCriteria,

    beforeSend: function (xhr) {

      xhr.setRequestHeader("Authorization", _headerForSearch.auth);

    },

    success: function(response) {


      console.log("response from okta enabled get api is: ",response)

    },

    error: function(xhr, status, error) {

      console.log("error from okta enabled get api is: ",xhr.responseText 

     + " " +status + " " + error );

    }

  });



  }

当我提出请求时,出现以下错误:-


从来源“ http://localhost: 3000”访问位于“ http://localhost :8000/ckcapp/api/posttest”的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否请求的资源上存在“Access-Control-Allow-Origin”标头。


我的 spring-boot 应用程序具有以下配置:


CORSFilter

    public class CORSFilter implements Filter {



    private static final String ONE_HOUR = "3600";


      @Override

      public void init(FilterConfig filterConfig) throws ServletException 

    {

      }


守候你守候我
浏览 179回答 2
2回答

噜噜哒

我通常使用一个 bean 来配置我的 CORS 设置。@Beanpublic FilterRegistrationBean<CorsFilter> simpleCorsFilter() {    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();    CorsConfiguration config = new CorsConfiguration();    config.setAllowCredentials(true);    config.setAllowedOrigins(Collections.singletonList("*"));    config.setAllowedMethods(Collections.singletonList("*"));    config.setAllowedHeaders(Collections.singletonList("*"));    source.registerCorsConfiguration("/**", config);    FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);    return bean;}

森林海

我将 React 与 Spring JWT 一起使用时遇到了与 CORS 策略阻止的类似问题。添加http.cors()到我的 SecurityConfigurer 类中以解决@EnableWebSecuritypublic class SecurityConfigurer extends WebSecurityConfigurerAdapter {&nbsp; &nbsp; @Override&nbsp; &nbsp; protected void configure(HttpSecurity http) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; http.cors().and().csrf().disable().......&nbsp; &nbsp; }}控制器@CrossOrigin(origins = {"http://localhost:3000"})@RestController
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java