我有一个springboot
应用程序,我正在制作一个后端API电子邮件验证系统。post方法正常工作,但我在使用GetMapping
注解时遇到了问题,不知道为什么它会返回一个404 Status Code Error
。
下面是代码:
@RestController
@RequestMapping("/api")
public class EmailVerificationEndpoint {
private final JavaMailSender javaMailSender;
private final EmailProperties emailProperties;
private final UserRepository userRepository; // Autowire the UserRepository
@Autowired
public EmailVerificationEndpoint(JavaMailSender javaMailSender, EmailProperties emailProperties, UserRepository userRepository) {
this.javaMailSender = javaMailSender;
this.emailProperties = emailProperties;
this.userRepository = userRepository;
}
@PostMapping("/send-verification-email")
public ResponseEntity<String> sendVerificationEmail(@RequestBody EmailRequest emailRequest) {
try {
// This works fine
} catch (MessagingException | UnsupportedEncodingException e) {
// Handle exceptions (e.g., email sending failure) here
// You can log an error message or return an error response to the frontend
e.printStackTrace();
return ResponseEntity.badRequest().body("Error sending email");
}
}
@GetMapping("/verify-email")
public ResponseEntity<String> verifyEmail(@RequestParam String token) {
try {
System.out.println("Gets on GET");
// Look up the user in your database by the provided token
User user = userRepository.findByVerificationToken(token);
if (user != null) {
System.out.println("User found with verification token: " + token);
// Mark the user as verified in your database
user.setVerified(true);
userRepository.save(user);
// You can also return a success response or redirect to a confirmation page
return ResponseEntity.ok("Email verified successfully");
} else {
// Token is not valid or user doesn't exist
return ResponseEntity.notFound().build(); // Return a 404 status code
}
} catch (Exception e) {
// Handle exceptions here
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred");
}
}
}
有没有人能帮我看看这是怎么回事?我一直在尝试的都不起作用...
1条答案
按热度按时间hgtggwj01#
我认为在这些不同的地方可能会有问题:
findByVerificationToken
方法运行了错误的查询。顺便说一下,我个人会写一些不同的代码,尽可能少地将代码放在try/catch块中。