java 无法向Sping Boot 服务器发出POST请求

kxxlusnw  于 2023-09-29  发布在  Java
关注(0)|答案(2)|浏览(126)

我正在做一个有控制器的Sping Boot 应用程序。应用程序运行在一个域上,当我试图通过http的链接发出POST请求时,我得到了一个405错误,但是当通过https发出请求时,一切都正常,最奇怪的是,GET方法http或https无关紧要,它在两种情况下都正常。下面是控制器的代码和请求的示例。

@Slf4j
@RestController
@CrossOrigin("*")
@Tag(name = "Quiz")
@RequiredArgsConstructor
@RequestMapping("/api/quiz")
public class QuizController {

    private final QuizService quizService;

    @Operation(
            description = "Creating quiz",
            summary = "Creating new quiz by dto and sending message to users",
            responses = {
                    @ApiResponse(description = "Success", responseCode = "201"),
                    @ApiResponse(description = "Quiz with this name already exists", responseCode = "400")})
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public void createQuiz(@RequestBody QuizDataDTO quizDataDTO) {
        quizService.createQuiz(quizDataDTO);
        quizService.spreadQuiz(quizDataDTO.getTelegramUsersIds());
        log.info("Create quiz with name {}", quizDataDTO.getQuizDTO().getQuizName());
    }

    @Operation(description = "Get links",
            summary = "Getting all links from google sheets lists",
            responses = @ApiResponse(description = "Success", responseCode = "200"))
    @GetMapping("/links")
    @ResponseStatus(HttpStatus.OK)
    public List<QuizDetailsDTO> getAllQuizs() {
        log.info("Return all quiz");
        return quizService.getAllQuizs();
    }
}

Use POST to http
我尝试在配置文件中配置CORS。它不工作

ie3xauqp

ie3xauqp1#

你可以使用Bean,我希望为你工作

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:8080");
        }
    };
}
j8yoct9x

j8yoct9x2#

我添加了这样一个配置类,它没有帮助

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*");
    }
}

相关问题