Spring Boot 继续获取“请求的资源上不存在'Node-Control-Allow-Origin'标头””

lc8prwob  于 2024-01-06  发布在  Spring
关注(0)|答案(1)|浏览(122)

我正在做一个任务管理器项目,前端用react,后端用Springboot。
当试图登录时(调用POST“http://localhost:8080/api/user/login”),但我一直得到相同的消息:

  1. Access to XMLHttpRequest at 'http://localhost:8080/api/user/login' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

字符串
我尝试了@CrossOrigin注解和做一个WebMvcConfigurer bean,但什么都没有。
这就是CorsConfig

  1. @Configuration
  2. public class CorsConfig {
  3. @Bean
  4. public WebMvcConfigurer corsConfigurer() {
  5. return new WebMvcConfigurer() {
  6. @Override
  7. public void addCorsMappings(CorsRegistry registry) {
  8. registry.addMapping("/**")
  9. .allowedOrigins("http://localhost:5173")
  10. .allowedMethods("*")
  11. .allowedHeaders("*")
  12. .exposedHeaders("*")
  13. .allowCredentials(true);
  14. }
  15. };
  16. }
  17. }


这就是我从前端发出请求的方式:

  1. const signin = async (user) => {
  2. try {
  3. console.log("User to be logged in: ");
  4. console.log(user);
  5. const res = await loginRequest(user);
  6. setUser(res.data);
  7. setIsAuthenticated(true);
  8. } catch (error) {
  9. console.log(error);
  10. setErrors(() => [error.response.data]);
  11. }
  12. };


有问题的登录请求:

  1. export const loginRequest = (user) => axios.post("/user/login", user);


最后是用户控制器类

  1. @RestController
  2. @RequestMapping("/user")
  3. public class UserController {
  4. private final UserService userService;
  5. @Autowired
  6. public UserController(UserService userService) {
  7. this.userService = userService;
  8. }
  9. @GetMapping("/login")
  10. public ResponseEntity<String> loginUser(@RequestBody User user) throws UserNotFoundException, WrongPasswordException {
  11. userService.loginUser(user);
  12. return ResponseEntity.ok("The user has logged in");
  13. }
  14. @PostMapping("/register")
  15. public ResponseEntity<String> registerUser(@RequestBody User user) throws InvalidUserNameException {
  16. userService.registerUser(user);
  17. return ResponseEntity.status(HttpStatus.CREATED).body("The user has successfully been created");
  18. }
  19. }


我已经尝试了@CrossOrigin(origins =“*”)和@CrossOrigin(origins =“http://localhost:5173”),以及所有类似的事情,指定允许的方法,头等。
提前感谢你的帮助,我超级卡住了,一直在寻找一个答案,现在已经有3个小时了,什么都没有。

szqfcxe2

szqfcxe21#

问题是我向服务器发出了一个POST请求,而它应该是一个GET请求。新手错误。
谢谢@Feelfree指出这一点!

相关问题