Code: Select all
@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);
}
};
}
}
Code: Select all
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);
}
}
}
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>
Ich habe es auch versucht: < /p>
const response = await fetch(`http://localhost:3000/delete-event?id=${id}`, {...
const response = await fetch(`http://localhost:8080/delete-event?id=${id}`, {...
< /code>
Wie kann ich Daten erhalten und speichern, aber nicht löschen? Ich dachte, vielleicht blockiert der Browser aufgrund von CORs, aber ich habe das abgedeckt. Kann jemand sehen, was ich falsch mache?