I am having some issues with my angular + springboot website..
When i try to get from by backend, it works just fine.
BUT when i try to POST (add new user) to the backend, i get an error:
Access to XMLHttpRequest at 'http://localhost:8080/api/users/add' from origin '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.
POST http://localhost:8080/api/users/add net::ERR_FAILED
My frontend service:
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 );
}
);
}
backend:
UserController.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);
}
userService.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);
}
SecurityConfigurer.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();
}
}
Here is the request body:
{"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}
Here is the users DB table:
thank you !