网站搜索

typescript - Angular 7 中错误的 URL 拼接


当我在我的项目中导航到不同的页面时,控制台显示带有错误 URL 的 404 错误。它看起来是这样的:

https://localhost:4420/example.com/api/customers

而它应该看起来像:

https://example.com/api/customers

当我针对 example.com API 时,我在项目中没有指定使用 localhost:4220 API。

这是我的 environment.ts:

export const environment = {
  production: false,
  baseUrl: 'example.com/',
  apiUrl: 'example.com/api/'
};

这里是我使用该服务的方式:

export class CustomersComponent implements OnInit  {
  customers: any;

  constructor(private http: HttpClient) { }

  ngOnInit() {
    const token = localStorage.getItem('jwt');
    this.http.get(environment.apiUrl + 'customers', {
      headers: new HttpHeaders({
        'Authorization': 'Bearer ' + token,
        'Content-Type': 'application/json'
      })
    }).subscribe(response => {
      this.customers = response;
    }, err => {
      console.log(err);
    });
  }
}

如果我从上面的代码中移除 environment.apiUrl +,我会得到

请求 URL: http://localhost:4220/customers

那么,部分“localhost:4420/”是从哪里来的,它是在哪里连接的?

答案#1

尝试将环境文件更改为 https 协议,如下所示 -

export const environment = {
  production: false,
  baseUrl: 'https://example.com/',
  apiUrl: 'https://example.com/api/'
};