我目前正在开发一个网站,该网站的后端是用 Java Spring Boot 制作的。但每次我发出删除或放置请求时,控制台中都会出现以下错误:
从源“http://localhost:3000”获取“http://10.0.10.67:8080/users/2”的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
我尝试了很多方法,但没有任何效果。我知道这不可能是后端的问题,因为删除请求在用邮递员发送时可以工作。
这是我删除用户的功能:
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)
}
}
这是我在后端的控制器类(就像我说的,删除功能在后端工作,我手动测试了它):
公共类ApplicationUserController { 私有最终 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");
}
}
}
我在“onClick(() => {})”中调用该函数,这似乎有效。
如果有人能为我解决问题,我将不胜感激。
Ps:我已经尝试过@CrossOrigin注解了,没用
从浏览器发送请求与使用 Postman 发送请求完全不同。您不会像 Postman 那样直接访问后端。浏览器会为你做到这一点。为了更好地理解它,您可以阅读更多关于跨域资源共享。
您的错误来自您的后端配置。您可以使用 CorsConfigurer。此外,您还可以将其与 Spring Security 结合使用。
请注意,您可以根据您的 Spring Boot 版本使用 allowedOrigins 或 allowedOriginsPattern 。
让我知道如何进一步帮助您。
我可以通过创建一个“配置”包并在其中添加以下类来修复错误:
@Configuration
public class CorsConfiguration
{
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE");
}
};
}
}
这个类是全局的,它允许每个人访问在所有控制器上放置删除后和获取请求