Код: Выделить всё
@SpringBootApplication
@ComponentScan(basePackages = { "net.tekknow.medaverter.*" })
@EntityScan(basePackages = "net.tekknow.medaverter.*")
public class MedaverterApplication {
public static void main(String[] args) {
SpringApplication.run(MedaverterApplication.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
};
}
}
Код: Выделить всё
package net.tekknow.medaverter.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.util.List;
import net.tekknow.medaverter.models.Event;
import net.tekknow.medaverter.repository.EventRepo;
@CrossOrigin
@RestController
public class EventController {
@Autowired
EventRepo eventRepo;
@GetMapping("/get-events")
public List getEvents(int user_id) {
List events = eventRepo.findEventsByUserId(user_id);
return events;
}
@PostMapping(path = "/save-event", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public ResponseEntity addEvent(@RequestBody Event event) {
return ResponseEntity.ok().body(eventRepo.save(event));
}
@DeleteMapping("/delete-event/{id}")
public ResponseEntity deleteEvent(@PathVariable Integer id) {
try {
eventRepo.deleteById(id);
return new ResponseEntity("Item deleted successfully", HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity("Error deleting item", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
events.tsxобразного/>>>>const deleteEvent = async (id: GridRowId) => {
const response = await fetch(`/delete-event?id=${id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json' // Or the appropriate content type
},
})
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
console.log('Row deleted successfully:', data);
})
.catch((error) => {
console.error('Error deleting row:', error);
});
}
< /code>
Я также попробовал: < /p>
const response = await fetch(`http://localhost:3000/delete-event?id=${id}`, {...
const response = await fetch(`http://localhost:8080/delete-event?id=${id}`, {...
< /code>
Как получается, что я могу получить и сохранить данные, но не удалять? Я думал, что, может быть, браузер блокировался из -за CORS, но я это покрыл. Кто -нибудь может увидеть, что я делаю не так?
Подробнее здесь: https://stackoverflow.com/questions/796 ... -404-error