angular - REST 适用于获取所有用户,但无法让一位用户说请求的资源上不存在“Access-Control-Allow-Origin”标头
问题描述
我在这里有点迷路,我有两个应用程序正在运行,一个 spring-boot 后端和一个 angular 8 前端,在后端我有一个应该在第一次访问时UserApi
返回一个用户的东西,我得到了我的用户从数据库。我这样做List
localhost: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"}`);
}
}
为此HttpConfig
,UserService.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
但我似乎无法克服这一点,有什么我遗漏的吗?
解决方案
好的,我发现了问题,
在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
,我需要为此找到正确的类型或更改参数数据类型
推荐阅读
- python-3.x - 如何使用 PythonPing 处理错误异常?
- azure - Azure Active Directory JWT 公钥更改
- javascript - 使用单个反应组件编辑嵌套对象属性的最佳方法?
- bash - ssh bash -c 重定向到文件不起作用
- python - 如何正确导入 python-keycloak
- swift - 自 iOS 13 起无法更改 UISearchTextField 的大小
- java - 导出到 jar 后找不到 Spring Boot application.properties
- docker - 创建容器时,我遇到了 docker npm install 问题
- ruby - 在 Ruby 中执行冒泡排序的最佳方法是什么?
- javascript - 从主站点操作异地 iframe 布局