首页 > 解决方案 > 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
  }
}

我的问题:什么会出错,以至于在创建新记录时,前后之间的通信不会发生?我应该添加其他东西吗?我很坚持这一点,因为我看不到问题

标签: angularspring-bootangular-httpclient

解决方案


export const environment = {
  production: false,
  baseUrl: 'http://localhost:8080/'
};

在您的环境 ts 文件中设置基本 url


推荐阅读