angular - Angular 和 Spring 之间通过 API 通信失败的原因是什么?
问题描述
我已经开始使用 Angular 11 和 Spring Boot 创建一个项目,但是我在通过API
. 从 Tomcat 服务器开始,它从port 8080 in the path ''
. 但是在创建新记录时,它会向我显示错误POST http://localhost:4200/api/client 404 (Not Found)
。
这是我的controler.java
:
@RequestMapping("/api/client")
public class ClienteController {
@GetMapping({"/", ""})
public List<Cliente> getAll() throws CMException {
return clienteService.findAll();
}
@PostMapping({"/", ""})
public Cliente create(@RequestBody Cliente cliente) throws CMException {
return clienteService.create(cliente);
}
}
这是我的environment.ts
:
export const environment = {
production: false,
baseUrl: '/api'
};
这是我的client.service.ts
:
const PREFIX = `${environment.baseUrl}/client`;
@Injectable()
export class ClientService implements IForm<Client> {
constructor(
private http: HttpClient
) {}
public list(filter: any = {}): Observable<Client[]> {
return this.http.get<Client[]>(PREFIX, {params: filter});
}
public create(client: Client): Observable<Client> {
return this.http.post<Client>(PREFIX, client);
}
}
这是我的component.ts
:
save() {
if (this.formNew.valid) {
if (this.isNew) {
this.clientService.create(this.formNew.value).subscribe(client => {
console.log(`New client: ${cliente.id}`);
this.back();
}, error => {
console.log(`Error client: ${error}`);
});
}
}
}
我创建了proxy.conf.json
具有以下参数的文件:
{
"/api/*": {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
我的问题:什么会出错,以至于在创建新记录时,前后之间的通信不会发生?我应该添加其他东西吗?我很坚持这一点,因为我看不到问题
解决方案
export const environment = {
production: false,
baseUrl: 'http://localhost:8080/'
};
在您的环境 ts 文件中设置基本 url
推荐阅读
- css - 在 CSS 网格布局中,我们是否从隐式网格线开始计算跨度?
- c++ - (!file) 和 (!file.is_open()) 有什么区别?
- calculus - 什么是 Hessian 矩阵?
- javascript - 为什么我在生成器增量时得到 NAN?
- monitoring - 按标签聚合指标
- docker - 将 Docker 中的 * 文件复制到目录会出错
- python - 在python curses中,我如何从用户那里获取字符串并同时在屏幕上打印
- r - compareGroups 包 - 导出文件时如何在 R 中指定目标路径?
- react-native - 使用反应导航处理嵌套堆栈导航器
- javascript - 在javascript中检查多个条件?