首页 > 解决方案 > 没有'Access-Control-Allow-Origin'标头存在springboot

问题描述

我的 angular + springboot 网站有一些问题..

当我尝试从后端获取时,它工作得很好。

但是当我尝试向后端发布(添加新用户)时,出现错误:

从源“http://localhost:4200”访问“http://localhost:8080/api/users/add”的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否请求的资源上存在“Access-Control-Allow-Origin”标头。

POST http://localhost:8080/api/users/add net::ERR_FAILED

我的前端服务:

  addUser(user: User): void{
const HTTP_OPTIONS = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Allow-Methods': 'GET,POST, PUT, DELETE'
  })
};
const body = JSON.stringify(user);
console.log(body);

this.httpClient.post('http://localhost:8080/api/users/add', body, HTTP_OPTIONS).subscribe(
  (data: any) => {
    this.emitIntervenantsSubject(data);
    this.goToMainRoute();
  },
  (error) => {
    const message = 'server issue';
    this.emitErrorsSubject(message );
  }
);

}

后端:

用户控制器.java

  @RestController
  @RequestMapping("api/users")
  public class UserController {

  ....

  @CrossOrigin(origins = "http://localhost:8080")
  @PostMapping(path = "/add")
  public User addUser(@RequestBody User user){

  return userService.addUser(user);

  }

用户服务.java

public interface UserService {

Optional<User> getUser(Long id);
Optional <List<User>> getUsers(Long ... id);

User addUser(User user);
 }

UserServiceimpl.java:

@Service 
public class UserServiceimpl implements UserService {
private UserRepo userRepo;

..........


 @Override
 public User addUser(User user) {
return this.userRepo.save(user);
 }

安全配置器.java:

@Configuration
@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {

  private PasswordEncoder passwordEncoder;

  private final SecretKey secretKey;
  private final JwtConfig jwtConfig;

  public SecurityConfigurer(SecretKey secretKey, JwtConfig jwtConfig) {
    this.secretKey = secretKey;
    this.jwtConfig = jwtConfig;
  }

  @Autowired
  public void ApplicationSecurityConfig(PasswordEncoder passwordEncoder){
   this.passwordEncoder = passwordEncoder;
  }

  protected void configure(HttpSecurity http) throws Exception{
     http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and()
    .addFilter(new JwtUsernameAndPasswordAuthenticationFilter(authenticationManager(), jwtConfig, 
      secretKey))
    .addFilterAfter(new JwtTokenVerifier(secretKey, jwtConfig), 
            JwtUsernameAndPasswordAuthenticationFilter.class)
    .authorizeRequests().antMatchers("/api/**").permitAll()
    .anyRequest()
    .authenticated();
  }
 }

这是请求正文:

{"id":2,"interfaceName":"User","fname":"test","lname":"test","email":"test@gmail.com","phone":"1112223333","address":"1 test","username":"test","password":"121212","role":"I","active":true}

这是用户数据库表:

用户数据库表

谢谢你 !

标签: javaangulartypescriptspring-bootcors

解决方案


推荐阅读