否访问控制;发送删除请求时请求的资源上存在标头
我目前正在使用一个网站,该网站上有Java Spring Boot的后端。但是,每次我进行删除或PUT请求时,控制台中会出现以下错误:
访问从'http://10.0.10.67:8080/users/2'来自Origin的访问检查:没有“访问控制”标题在请求的资源上。如果不透明的响应满足您的需求,请将请求模式设置为“无库”,以通过禁用CORS来获取资源。
我尝试了多件事,没有任何效果。我知道这不是后端的问题,因为删除请求在向Postman发送时工作。
这是我用于删除用户的功能:
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)
}
}
,这是我在后端中的控制器类(就像我说的,删除函数在后端中起作用,我手动对其进行了测试):
公共类应用程序useplyuserController { 私人最终用户服务用户服务;
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(()=&gt; {})中调用该函数,这似乎有效。
如果有人可以为我解决问题,我将不胜感激。PS
:我已经尝试了@crossorigin notation,它没有工作
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从浏览器发送请求与与Postman一起发送的请求完全不同。您并没有像Postman的行为那样直接击中您的后端。浏览器为您做。为了更好地了解它,您可以在。
您的错误来自您的后端配置。您可以使用Corsconfigurer。另外,您可以将其与弹簧安全性结合使用。
请注意,您可以根据Spring Boot版本使用允许的运动或AllowerRiginsPattern。
spring启动启用crossorigin
让我知道我如何能帮助您进一步帮助您。
Sending a request from a browser is completely different than sending it with Postman. You are not hitting your backend directly like how Postman does. Browsers does it for you. To understand it better, you can read more on crossorigin resource sharing.
Your error comes from your backend configuration. You can use CorsConfigurer. Also, you can combine it with Spring Security.
Note that you can use allowedOrigins or allowerOriginsPattern according to your Spring Boot version.
spring boot enabling crossorigin
Let me know how I can help you further.
我可以通过创建“配置” -package并在其中进行
关注来解决该错误:此类是全局
I could fix the error, by creating a "configuration"-package and following class in it:
This Class is global and it allows everyone access to put post delete and get requests on all controllers