最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Spring Boot Todo App: POST request not working with React & Axios - Stack Overflow

programmeradmin3浏览0评论

I created a small Todo project using Spring Boot for the backend and React for the frontend. However, when I try to send a POST request from React using Axios, I encounter an error.

I want to make sure my POST request successfully sends data to my Spring Boot API. The design is not important—I just need a basic form that sends a request.

Here is my Spring Boot controller:

package com.example.todo.controller;

import com.example.todo.model.ToDoItem;
import com.example.todo.service.ToDoService;
import .springframework.http.HttpStatus;
import .springframework.http.ResponseEntity;
import .springframework.web.bind.annotation.*;

@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("/api/todos")
public class ToDoController {
    private final ToDoService toDoService;

    public ToDoController(ToDoService toDoService) {
        this.toDoService = toDoService;
    }

    @PostMapping
    public ResponseEntity<?> createToDo(@RequestBody ToDoItem todo) {
        ToDoItem savedTodo = toDoService.createToDo(todo);
        return ResponseEntity.status(HttpStatus.CREATED).body(
            new ResponseFormat("To-do item created successfully", savedTodo)
        );
    }

    // Вспомогательный класс для кастомного ответа
    private static class ResponseFormat {
        public String message;
        public ToDoItem todo;

        public ResponseFormat(String message, ToDoItem todo) {
            this.message = message;
            this.todo = todo;
        }
    }
}

TodoItem.java

package com.example.todo.model;

import jakarta.persistence.*;

@Entity
@Table(name = "todos", uniqueConstraints = @UniqueConstraint(columnNames = "title"))
public class ToDoItem {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String title;

    @Column(nullable = false)
    private String description;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private Priority priority;

    @Column(nullable = false)
    private boolean completed = false;

    public ToDoItem() {
    }

    public ToDoItem(String title, String description, Priority priority) {
        this.title = title;
        this.description = description;
        this.priority = priority;
        thispleted = false;
    }

    // Геттеры и сеттеры
    public Long getId() { return id; }
    public String getTitle() { return title; }
    public String getDescription() { return description; }
    public Priority getPriority() { return priority; }
    public boolean isCompleted() { return completed; }

    public void setId(Long id) { this.id = id; }
    public void setTitle(String title) { this.title = title; }
    public void setDescription(String description) { this.description = description; }
    public void setPriority(Priority priority) { this.priority = priority; }
    public void setCompleted(boolean completed) { thispleted = completed; }
}

TodoService.java

package com.example.todo.service;

import com.example.todo.model.ToDoItem;
import com.example.todo.model.Priority;
import com.example.todo.repository.ToDoRepository;
import .springframework.http.HttpStatus;
import .springframework.stereotype.Service;
import .springframework.web.server.ResponseStatusException;

@Service
public class ToDoService {
    private final ToDoRepository toDoRepository;

    public ToDoService(ToDoRepository toDoRepository) {
        this.toDoRepository = toDoRepository;
    }

    public ToDoItem createToDo(ToDoItem todo) {
        // Проверяем уникальность title
        if (toDoRepository.findByTitle(todo.getTitle()).isPresent()) {
            throw new ResponseStatusException(HttpStatus.CONFLICT, "Title must be unique");
        }

        // Проверяем корректность priority
        if (todo.getPriority() == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid priority");
        }

        return toDoRepository.save(todo);
    }
}

TodoAplplication.java

package com.example.todo;

import .springframework.boot.SpringApplication;
import .springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TodoApplication {

    public static void main(String[] args) {
        SpringApplication.run(TodoApplication.class, args);
    }

}

application.properties -->>

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=update

Priority.java

package com.example.todo.model;

public enum Priority {
    LOW, MEDIUM, HIGH
}

Repository.java

package com.example.todo.repository;

import com.example.todo.model.ToDoItem;
import .springframework.data.jpa.repository.JpaRepository;
import .springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface ToDoRepository extends JpaRepository<ToDoItem, Long> {
    Optional<ToDoItem> findByTitle(String title);
}


发布评论

评论列表(0)

  1. 暂无评论