Spring Boot对接Angular发起POST请求触发CORS跨域错误问题求助
问题修复方案
核心原因说明
你看到的CORS报错是表面现象,核心原因是接口定义错误导致请求404,Spring返回的404响应默认不会携带CORS头,所以触发了浏览器的跨域拦截规则,Postman不校验跨域所以请求能正常运行。
具体修复步骤
1. 修正后端接口映射规则
现有接口存在两处错误:路径占位符无分隔符、路径占位符和@RequestParam参数逻辑不匹配,修正后代码如下:
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')") @RequestMapping(value = "/addCartItem", method = RequestMethod.POST ) public List<CartItem> addCartItem(@RequestParam Long cartId , @RequestParam Long productId) { return cartService.addCartItem(cartId ,productId); }
2. 修正前端Angular请求参数传递逻辑
现有写法错误将查询参数放到了请求体中,需要将参数放到POST请求的第三个配置项的params属性中,修正后代码如下:
addCartItem(cartId:number,productId:number):Observable<any>{ const httpParams = new HttpParams({ fromObject:{ cartId: cartId.toString(), productId: productId.toString(), } }) return this.httpClient.post('http://localhost:8080/api/user/addCartItem', null, { params: httpParams }) }
3. 补全Spring Security预检请求放行规则
浏览器发送CORS预检请求时不会携带身份凭证,需要单独放行OPTIONS类型的请求避免被安全框架拦截,同时修正安全配置类的拼写错误:
// 类名修正为正确的SecurityConfig @EnableWebMvc @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity( prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired UserDetailsServiceImpl userDetailsService; @Autowired private AuthEntryPointJwt unauthorizedHandler; @Bean public AuthTokenFilter authenticationJwtTokenFilter() { return new AuthTokenFilter(); } @Override public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable() .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests() // 新增OPTIONS预检请求放行规则 .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() .antMatchers("/api/auth/**").permitAll() .antMatchers("/api/admin/**").permitAll() .antMatchers("/api/user/**").permitAll() .antMatchers("/api/public/**").permitAll() .anyRequest().authenticated(); http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); } @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedMethods("GET","POST","PUT","DELETE","OPTIONS") .allowedHeaders("*") .allowedOrigins("*"); } }; } }
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

