java - 没有'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}
这是用户数据库表:
谢谢你 !
解决方案
推荐阅读
- python - 测量opencv相机管道延迟
- php - 如何在 laravel 中的 each 方法中使用变量或依赖注入
- html - Bootstrap5 Stretched-link 不适用于简单的卡片
- java - 如何添加下一个列表来进行求和和平均?
- java - 可以告诉 Java FileVisitor 跳过文件并只返回文件夹路径吗?
- javascript - 如果使用 JavaScript 以百分比值表示 CSS 高度和宽度,如何获取它们?
- java - 使用模态 Swing 时如何在 Windows PC 上获得鼠标焦点?
- python - 最优联盟结构
- c# - C# 中 *is* 关键字的新条件语法
- python - python - TypeError:'NoneType'对象不可调用