我正在做一个任务管理器项目,前端用react,后端用Springboot。
当试图登录时(调用POST“http://localhost:8080/api/user/login”),但我一直得到相同的消息:
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
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:5173")
.allowedMethods("*")
.allowedHeaders("*")
.exposedHeaders("*")
.allowCredentials(true);
}
};
}
}
型
这就是我从前端发出请求的方式:
const signin = async (user) => {
try {
console.log("User to be logged in: ");
console.log(user);
const res = await loginRequest(user);
setUser(res.data);
setIsAuthenticated(true);
} catch (error) {
console.log(error);
setErrors(() => [error.response.data]);
}
};
型
有问题的登录请求:
export const loginRequest = (user) => axios.post("/user/login", user);
型
最后是用户控制器类
@RestController
@RequestMapping("/user")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/login")
public ResponseEntity<String> loginUser(@RequestBody User user) throws UserNotFoundException, WrongPasswordException {
userService.loginUser(user);
return ResponseEntity.ok("The user has logged in");
}
@PostMapping("/register")
public ResponseEntity<String> registerUser(@RequestBody User user) throws InvalidUserNameException {
userService.registerUser(user);
return ResponseEntity.status(HttpStatus.CREATED).body("The user has successfully been created");
}
}
型
我已经尝试了@CrossOrigin(origins =“*”)和@CrossOrigin(origins =“http://localhost:5173”),以及所有类似的事情,指定允许的方法,头等。
提前感谢你的帮助,我超级卡住了,一直在寻找一个答案,现在已经有3个小时了,什么都没有。
1条答案
按热度按时间szqfcxe21#
问题是我向服务器发出了一个POST请求,而它应该是一个GET请求。新手错误。
谢谢@Feelfree指出这一点!