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
130 views
in Technique[技术] by (71.8m points)

angularjs - 'http://localhost:4200' has been blocked by CORS policy:No 'Access-Control-Allow-Origin' header is present on the requested resource

I am trying to update the data using spring boot and angular, but whenever i try to update the data i got this error 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This is my spring controller and angular service.

I tried other solutions from stackoverflow but it doesn't work please tell me what i am doing wrong here..

InfoController.java

@RestController
@RequestMapping("/student")
public class InfoController {

@Autowired
private InfoDAO infoDAO;

@CrossOrigin(origins = "http://localhost:4200")

@PutMapping("/infos/{id}")
public List<Info> updateStudent(@RequestBody Info info, @PathVariable int id) {

    List<Info> information = infoDAO.getbyID(id);

    System.out.println("this is id");

    info.setId(id);

    infoDAO.update(info);

    // info1.update(info1);

    return information;
}

  } 

InfoDAO.java

List<Info> getbyID(int id);
boolean update(Info info);

InfoDAOImpl.java

public class InfoDAOImpl implements InfoDAO {

@PersistenceContext
@Autowired
private EntityManager em;

@Override
public List<Info> getbyID(int id) {
    String query = "FROM Info WHERE id = :id";
    return em
                .createQuery(query,Info.class)
                .setParameter("id",id)  
                .getResultList();
 }

public boolean update(Info info) {
    try {           
        em
                    .merge(info);
        return true;
    }
    catch(Exception ex) {       
        return false;
    }                   
}
}

SecurityConfig.java

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired DataSource dataSource;

@Override
protected void configure(HttpSecurity http) throws Exception { 
     http.
     cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
    .and().csrf().disable()
            .authorizeRequests()                                                                
            .antMatchers("/**").permitAll()
            .antMatchers("/login").hasRole("ADMIN")                                      
            .antMatchers("/Signup").hasRole("USER")
            .and()
            .exceptionHandling()
            .accessDeniedPage("/access-denied")
            .and()
            .addFilter(new JWTAuthenticationFilter(authenticationManager()))
            .addFilter(new JWTAuthorizationFilter(authenticationManager(), customUserDetailService));
}

@Bean   
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
    configuration.setAllowCredentials(true);
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
    configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Origin","Authorization", "Cache-Control", "Content-Type", "xsrfheadername","xsrfcookiename"
    ,"X-Requested-With","XSRF-TOKEN","Accept", "x-xsrf-token","withcredentials","x-csrftoken"));
    configuration.setExposedHeaders(Arrays.asList("custom-header1", "custom-header2"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration); 
    return source; 
}

Web.service.ts

export class WebService {

constructor(private httpClient: HttpClient) { }

serverUrl = 'http://localhost:8083/student';

editPlan(data: Student, id:any): Observable<any> {
    const url = `/infos/${id}`;
    return this.httpClient.put(this.serverUrl + url, data);
}

getWebPlanInfo(): Observable<any> {
    const url = '/plan/info';
    return this.httpClient.get(this.serverUrl + url);
}

}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This issue is with this Line cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues()).

If you remove this line it will work.

But how ? That is because your @Bean method corsConfigurationSource will be loaded by spring container during the runtime and it will create the Bean for this.

By adding this line cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues()) it overrides the Bean corsConfigurationSource.

This method applyPermitDefaultValues() in CorsConfiguration class will allow GET, POST, HEAD request methods by default. Due to this your PUT/DELETE method is not working.

Reference: https://github.com/spring-projects/spring-framework/blob/master/spring-web/src/main/java/org/springframework/web/cors/CorsConfiguration.java#L428


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

...