I'm currently working on a website, which has a backend made in Java Spring Boot. But everytime i make a delete or a put request, the following Error appears in the console:
Access to fetch at 'http://10.0.10.67:8080/users/2' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I've tried multiple things, and nothing worked. I know it can't be a problem of the backend, because delete requests work, when sending them with postman.
This is my function for deleting users:
export async function deleteUser(id, token) {
console.log("helo")
const response = await fetch(`${URL}/users/${id}`, {
method: "DELETE",
mode: 'cors',
headers: {
"content-type": "application/json",
"authorization": `Bearer ${token}`,
"Access-Control-Allow-Origin": "http://localhost:3000"
}
})
if (!response.ok) {
return Promise.reject(response)
}
}
And this is my controller class in backend (like i said, the delete function works in backend, i tested it manually):
public class ApplicationUserController { private final UserService userService;
private final TimeService timeService;
private final RfidChipService rfidChipService;
@Autowired
public ApplicationUserController(UserService userService, TimeService timeService, RfidChipService rfidChipService) {
this.userService = userService;
this.timeService = timeService;
this.rfidChipService = rfidChipService;
}
@Operation(summary = "Find ApplicationUser with a given firstname, lastname and/or email. If no parameters given, all users are returned.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "ApplicationUser(s) found",
content = {@Content(mediaType = "application/json",
schema = @Schema(implementation = ApplicationUser.class))})})
@GetMapping()
public ResponseEntity<?> findUserByNameSurnameEmail(@Parameter(description = "Users firstname to search") @RequestParam(required = false) String firstname,
@Parameter(description = "Users lastname to search") @RequestParam(required = false) String lastname,
@Parameter(description = "Users email to search") @RequestParam(required = false) String email) {
try {
if (StringUtils.isNotBlank(firstname)) {
return ResponseEntity.ok(userService.getUserByFirstname(firstname));
} else if (StringUtils.isNotBlank(lastname)) {
return ResponseEntity.ok(userService.getUserByLastname(lastname));
} else if (StringUtils.isNotBlank(email)) {
return ResponseEntity.ok(userService.getUserByEmail(email));
}
return ResponseEntity.ok(userService.getAllUsers());
} catch (EntityNotFoundException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No ApplicationUser(s) found");
}
}
@PostMapping(value = "/sign-up", consumes = "application/json")
@ResponseStatus(HttpStatus.CREATED)
public void signUp(@Parameter(description = "The new user to create") @Valid @RequestBody ApplicationUserDTO requestDTO) {
try {
List<RfidChipDTO> rfidChipDTOList = rfidChipService.getRfidChipWithNoUser();
requestDTO.setRfidChip(RfidChipMapper.fromDTO(rfidChipDTOList.get(0)));
userService.signUp(ApplicationUserMapper.fromDTO(requestDTO));
} catch (DataIntegrityViolationException e) {
throw new ResponseStatusException(HttpStatus.CONFLICT);
}
}
@Operation(summary = "Find a user by his id")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "ApplicationUser found",
content = {@Content(mediaType = "application/json",
schema = @Schema(implementation = ApplicationUser.class))}),
@ApiResponse(responseCode = "404", description = "ApplicationUser not found",
content = @Content)})
@GetMapping(path = "{id}")
public ResponseEntity<?> findById(@Parameter(description = "Id of user to get") @PathVariable Integer id) {
try {
return ResponseEntity.ok(userService.getById(id));
} catch (EntityNotFoundException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "ApplicationUser could not be found");
}
}
@Operation(summary = "Find admins employees by his id")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Employees found",
content = {@Content(mediaType = "application/json",
schema = @Schema(implementation = ApplicationUser.class))}),
@ApiResponse(responseCode = "404", description = "No Employees found",
content = @Content)})
@GetMapping(path = "{id}/employees")
public ResponseEntity<?> findEmployeesByAdminId(@Parameter(description = "Id of admin") @PathVariable Integer id) {
try {
return ResponseEntity.ok(userService.getUserByAdminId(id));
} catch (EntityNotFoundException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Admin could not be found");
}
}
@Operation(summary = "Find users times by his id")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Time(s) found",
content = {@Content(mediaType = "application/json",
schema = @Schema(implementation = ApplicationUser.class))}),
@ApiResponse(responseCode = "404", description = "No times found",
content = @Content)})
@GetMapping(path = "{id}/times")
public ResponseEntity<?> findTimesByUserId(@Parameter(description = "Id of user") @PathVariable Integer id) {
try {
return ResponseEntity.ok(timeService.findTimeByUserId(id));
} catch (EntityNotFoundException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User could not be found");
}
}
@Operation(summary = "Update a user")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "ApplicationUser was updated successfully",
content = {@Content(mediaType = "application/json",
schema = @Schema(implementation = ApplicationUser.class))}),
@ApiResponse(responseCode = "409", description = "ApplicationUser could not be updated",
content = @Content),
@ApiResponse(responseCode = "400", description = "Validation failed",
content = {@Content(mediaType = "application/json",
schema = @Schema(implementation = ApplicationUser.class))})})
@PatchMapping(value = "{id}", consumes = "application/json")
public ResponseEntity<?> update(@Valid @RequestBody ApplicationUserDTO applicationUserDTO, @PathVariable Integer id) {
try {
ApplicationUserDTO updatedUser = userService.update(applicationUserDTO, id);
return ResponseEntity.ok(updatedUser);
} catch (DataIntegrityViolationException e) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "ApplicationUser could not be updated");
}
}
@Operation(summary = "Create a new ApplicationUser")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "ApplicationUser was created successfully",
content = {@Content(mediaType = "application/json",
schema = @Schema(implementation = ApplicationUser.class))}),
@ApiResponse(responseCode = "409", description = "ApplicationUser could not be created",
content = @Content),
@ApiResponse(responseCode = "400", description = "Validation failed",
content = {@Content(mediaType = "application/json",
schema = @Schema(implementation = ApplicationUser.class))})})
@ResponseStatus(HttpStatus.CREATED)
@PostMapping(consumes = "application/json")
public ResponseEntity<?> create(@Valid @RequestBody ApplicationUserDTO applicationUserDTO) {
try {
ApplicationUserDTO createdApplicationUserDTO = userService.create(applicationUserDTO);
return ResponseEntity.status(201).body(createdApplicationUserDTO);
} catch (DataIntegrityViolationException | ConstraintViolationException e) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "ApplicationUser could not be created");
}
}
@Operation(summary = "Delete a user")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "ApplicationUser was deleted successfully",
content = {@Content(mediaType = "application/json",
schema = @Schema(implementation = ApplicationUser.class))}),
@ApiResponse(responseCode = "404", description = "ApplicationUser could not be deleted",
content = @Content)})
@DeleteMapping("{id}")
public ResponseEntity<?> delete(@PathVariable Integer id) {
try {
userService.deleteById(id);
return ResponseEntity.ok().build();
} catch (EmptyResultDataAccessException e) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "ApplicationUser could not be deleted");
}
}
}
I call the function in an "onClick(() => {}), and this seems to work.
I would appreciate it if someone could solve the problem for me.
Ps: I already tried the @CrossOrigin annotation, it didn't work
CodePudding user response:
Sending a request from a browser is completely different that sending it with postman. You are not hitting directly your backend like postman, browsers does it for you To understand it better you can read this one. crossorigin resource sharing
Your error comes from your backend configuration. You can use CorsConfigurer. Also you can combine it with spring security.
note: you can use allowedOrigins or allowerOriginsPattern according to your spring boot version.
spring boot enabling crossorigin
Let me know if I can help further.
CodePudding user response:
I could fix the error, by creating a "configuration"-package and following class in it:
@Configuration
public class CorsConfiguration
{
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE");
}
};
}
}
This Class is global and it allows everyone access to put post delete and get requests on all controllers