原点'http://localhost:4200'已被CORS策略阻止:No'访问控制允许来源&



我的后端是使用java springboot

@CrossOrigin(origins = "*", maxAge = 3600)//allow cross-origin resource sharing (CORS) request
@RestController
@RequestMapping("/api/school")
public class CourseController {
@PostMapping("/login")
public ResponseEntity<?> loginPage(@RequestBody LoginRequest loginRequest){
*****
Authentication authentication= authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(name, passowrd));
SecurityContextHolder.getContext().setAuthentication(authentication);
UserDetails userDetails = (UserDetails)authentication.getPrincipal();
LoginResponse loginResponse =new LoginResponse();
loginResponse.setUsername(userDetails.getUsername());
return ResponseEntity.ok(loginResponse);
}
@GetMapping("/apartment/{apartmentName}")
public ResponseEntity<?> findTeachers(@PathVariable("apartmentName")String apartName){
******
return ResponseEntity.ok(list);

}
}
my web security config:
@Configuration
@EnableWebSecurity //it's allow the static resource, image, css, js..
@EnableGlobalMethodSecurity(prePostEnabled = true) //allow the multiple endpoint
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors()
.and().csrf().disable()
.authorizeHttpRequests()
.antMatchers("/api/school/login").permitAll() // login do not need to authenticated
.anyRequest().authenticated()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().httpBasic();

}
}

前端角度,

export class CourseService {
private baseUrl = 'http://localhost:9010/api/school';
constructor(private _httpClient: HttpClient) {}
login(request: LoginRequest): Observable<LoginResponse> {
return this._httpClient
.post<LoginResponse>(this.baseUrl + '/login', request)
.pipe(catchError(this.errorHandler));
}
getAllTeachers(apartmentName: string): Observable<TeachersResponse[]> {
return this._httpClient
.get<TeachersResponse[]>(this.baseUrl + '/apartment/' + apartmentName)
.pipe(catchError(this.errorHandler));
}

我可以访问课程页面的登录页面(输入用户名、密码(,但当我输入apartmentName作为输入时,单击按钮调用组件方法。显示错误来源'http://localhost:4200'已被CORS策略阻止:请求的资源上不存在"Access Control Allow Origin"标头。我的控制器有@CrossOrigin(origins="*",maxAge=3600(,我更改了@CrossOriginal(origins="*"(;http://localhost:4200"(也不起作用,并且WebSercurty配置有http.cors((。为什么我仍然有这个错误?

Component method call courseService
loadData(apartmentName: string) {
console.log('call courseService');
this._courseService.getAllTeachers(apartmentName).subscribe((teachers) => {
this.teacherArray = teachers;
console.log(teachers);
});
}

嘿,我试着在控制器方法中添加@CrossOrigin,但不起作用。因此,我在SecurityConfig类中添加了公共的CorsConfigurationSource configurationSource(({},使其工作。和评论@CrossOrigin。

public CorsConfigurationSource configurationSource() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
//allow the url
corsConfiguration.addAllowedOrigin("http://localhost:4200");
//allow the http method
corsConfiguration.addAllowedMethod("*");
//allow the http heard
corsConfiguration.addAllowedHeader("*");
corsConfiguration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
//allow all url
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return urlBasedCorsConfigurationSource;
}

在SecurityFilterChain添加

.and().cors().configurationSource(configurationSource());

相关内容

最新更新