我目前正在一个网站上工作,它有一个后端在Java Spring Boot。但每次我做一个删除或放请求,下面的错误出现在控制台中:
访问获取"http://10.0.10.67:8080/用户/2"起源的http://localhost: 3000已经被歌珥政策:应对起飞前的请求没有通过访问控制检查:没有提供"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 {
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注释,它不起作用
发送请求从浏览器完全不同与邮递员发送它。你不像邮差一样直接击中你的后端,浏览器为你做了这件事为了更好地理解它,你可以阅读这篇文章。跨域资源共享
你的错误来自你的后端配置。你可以使用CorsConfigurer。您也可以将它与spring security结合使用。
注意:你可以根据你的spring boot版本使用allowedOrigins或allowerOriginsPattern。
弹簧启动启用交叉加载
如果还需要我帮忙,请告诉我。
我可以修复这个错误,方法是创建一个"configuration"包,并在其中添加class:
@Configuration
public class CorsConfiguration
{
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE");
}
};
}
}
这个类是全局的,它允许每个人访问所有控制器上的post delete和get请求