首页 > 解决方案 > REST 适用于获取所有用户,但无法让一位用户说请求的资源上不存在“Access-Control-Allow-Origin”标头

问题描述

我在这里有点迷路,我有两个应用程序正在运行,一个 spring-boot 后端和一个 angular 8 前端,在后端我有一个应该在第一次访问时UserApi返回一个用户的东西,我得到了我的用户从数据库。我这样做Listlocalhost:4200

@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("api/")
public class UserApi {

    @Autowired
    private UserService userService;

    @GetMapping("users")
    public List<User> getUsers() {
        return userService.findAllUsers();
    }
    }

在前面我有以下

export class UserService extends HttpConfig {

  getUsers(): Observable<User[]> {
    return this.http().get<User[]>(`${this.getBaseUrl() + "/users"}`);
  }
}

为此HttpConfigUserService.ts文件扩展简单明了,看起来像

export class HttpConfig {

  private baseUrl = "http://localhost:8080/api";

  constructor(private httpClient: HttpClient) { }

  getBaseUrl(){
    return this.baseUrl;
  }

  http(){
    return this.httpClient;
  }
}

但是只要我想通过发送一些参数,我就会在浏览器上得到以下内容

Access to XMLHttpRequest at 'http://localhost:8080/api/example/getUser' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

为此,后端在UserApi.class

    @GetMapping("{userName:[\\d]+}/getUser")
    public User findUserByName(final @PathVariable String userName) {
        return userService.getUserByName(userName);
    }

在前面UserService.ts我有这个

  getOneUser(userName: string): Observable<User> {
    return this.http().get<User>(`${this.getBaseUrl() + "/" + userName + "/getUser"}`);
  }

对于UserComponent.ts我做了以下

export class UserComponent implements OnInit {

  users: User[];
  user: User;

  constructor(private userService: UserService) {
  }

  ngOnInit(): void {
    this.userService.getUsers().subscribe((users: User[]) => {
      this.users = users;
    });
  }

  getUserByName(userName: string): void{
    console.log(userName);
    this.userService.getOneUser(userName).subscribe((user: User) => {
      this.user = user;
    });
  }
}

据我所知,注释 RestController 应该 @CrossOrigin(origins = "http://localhost:4200") 可以解决,CORS Policy但我似乎无法克服这一点,有什么我遗漏的吗?

标签: angularspring-bootrestcors

解决方案


好的,我发现了问题,

在api中的findByUserName方法

@GetMapping("getUser/{userName:[\\d]+}")
public User findUserByName(final @PathVariable("userName") String userName) {
    System.out.println(userName);
    return userService.getUserByName(userName);
}

the[\\d]仅指数字@GetMapping("getUser/{userName:[\\d]+}")

类似于传递一个Integer但期望的Long,我需要为此找到正确的类型或更改参数数据类型


推荐阅读