【问题标题】:springboot for backend reactjs frontendspringboot 用于后端 reactjs 前端
【发布时间】:2021-05-02 14:05:24
【问题描述】:

我使用 springboot 和 reactjs 在为后端添加安全性之前一切正常,现在去网页检索我的数据,我在那里看不到任何数据。我去控制台它说用户名未定义:不知道这是什么意思。

跨域请求被阻止:同源策略不允许读取位于 http://localhost:8080/users/undefined/todos 的远程资源。 (原因:CORS 请求没有成功)

更新:我尝试了两种代码但没有帮助。 这是否意味着任何严重的事情:

 "Uncaught (in promise) Error: Network Error
    at createError" (createError.js:16)

Access to XMLHttpRequest at 'http://localhost:8080/users/undefined/todos' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
xhr.js:177 GET http://localhost:8080/users/undefined/todos net::ERR_FAILED
dispatchXhrRequest @ xhr.js:177
xhrAdapter @ xhr.js:13

todos:1 Access to XMLHttpRequest at 'http://localhost:8080/users/undefined/todos' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
xhr.js:177 GET http://localhost:8080/users/undefined/todos net::ERR_FAILED
dispatchXhrRequest @ xhr.js:177
xhrAdapter @ xhr.js:13
dispatchRequest @ dispatchRequest.js:52

createError.js:16 Uncaught (in promise) 错误:网络错误 在 createError (createError.js:16)

【问题讨论】:

  • 您确定您的 Spring 应用程序正在运行吗?如果是这样,请发布后端的堆栈跟踪。

标签: reactjs spring spring-boot


【解决方案1】:

添加@CrossOrigin(origins = "http://localhost:3000")(如果您在 3000 运行客户端),或使用此 bean(在 SecurityConfig 中):

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setExposedHeaders(Arrays.asList("x-auth-token", "xsrf-token"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

【讨论】:

    猜你喜欢
    • 2018-04-21
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-17
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    相关资源
    最近更新 更多