Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

spring - springboot for backend reactjs frontend

i use springboot and reactjs everthing was working before adding security to backend, now as go to web page to retrieve my data, i do not see any data there. I go to console it says the username not defined:do not know what does it mean.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/users/undefined/todos. (Reason: CORS request did not succeed)

UPDATE: I tried to both code but did not help. does this mean anything serious:

 "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) Error: Network Error at createError (createError.js:16)

question from:https://stackoverflow.com/questions/65941160/springboot-for-backend-reactjs-frontend

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add @CrossOrigin(origins = "http://localhost:3000") (if you run your client at 3000), or use this bean (in 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;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...