【问题标题】:Why http://localhost:4200 is appended to HttpClient API?为什么 http://localhost:4200 附加到 HttpClient API?
【发布时间】:2020-07-04 01:24:08
【问题描述】:

我正在使用 Angular7。

当我进行 API 调用时,Angular 应用程序 URL 也附加到 URL

const payload = {
        id: 1,
        name: 'ABC
    };
    const httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
        }),
    };
  this.http.post("http://localhost:8080/my-server/getData", payload, httpOptions);

例如:http://localhost:4200/http://localhost:8080/my-server/getData

导致 404 错误。

使用"@angular/http": "7.2.11",

【问题讨论】:

  • 你有角度拦截器(可能是为 ssr 设置的)或角度开发设置代理吗?

标签: angular angular7 angular8 angular-httpclient angular-http


【解决方案1】:

不需要添加 localhost 你只需要调用 /my-server/getData 和 url 将是 本地主机:4200/my-server/getData。

【讨论】:

  • 我的服务器 isde 应用程序正在另一个服务器 Tomcat 中运行,端口为 8080。所以如果我删除 localhost,那么整个 url 将是错误的
  • 这将调用api方法。你可以让它运行而不需要调用
【解决方案2】:
    Ok, first create 
    1. Util.ts file -- 
    import * as pe from 'parse-error';
    import { environment } from '../../environments/environment';
export class Util {
    static async post(url, data, isFormData?: any) {
        var headers = new Headers();
        if (url[0] == '/'){
          url = this.getApiUrl() + url;
          headers = this.apiHeaders(headers, isFormData);
        }
        let err, res;
        [err, res] = await this.to(this.http.post(url, data, { headers: headers }).toPromise(), false);
        return this.responder(err, res);
      }
      static to(promise, parse?) {// global function that will help use handle promise rejections, this article talks about it http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/
        return promise.then(data => {
          return [null, data];
        }).catch(err => {
          if (parse === false) return [err];
          return [pe(err)]
        });
      }
      static getApiUrl(){
        return environment.apiUrl;
      }
      static apiHeaders(headers: any, isFormData?: any) {
        if (isFormData !== undefined) {
          headers.append('mimeType', 'multipart/form-data');
        } else {
         headers.append('Content-Type', 'application/json');
        }
        let user:User = <User> User.Auth();
        if (user){
          let token: string = user.token;
          headers.append('Authorization', token);
        }
        return headers;
      }
      static responder(err, res){
        let send;
        if (err) send = err;
        if (res) send = res;
        return JSON.parse(send._body);
      }
}
 1. Update environment file -- 
       <code>
export const environment = {
    production: false,
    apiUrl: 'http://localhost:8080'
  };
    </code>
 2. Update your Component - 
 <code>
    import { Util } from './../helpers/util.helper';
    static async getBuLevelResult(startDate, endDate,  otherData?: any) {
      let err, res; // get from API
      const u_id = this.getlocalStorage('User');
      let dataSet: any;
      dataSet = {
        'startDate': startDate + ' 00:00:00',
        'endDate': endDate + ' 23:59:00'
      };
      if (otherData) {
        dataSet.projectId = otherData.projectId;
      }
      [err, res] = await Util.to(Util.post('/selfService/user/' + u_id[0].userId + '/dashboard/piechart/getBuLevelData', dataSet));
      if (err) {
        Util.TE(err.message, true);
      } else {
        return res.data;
      }
    }

</code>

      

【讨论】:

    猜你喜欢
    • 2016-11-28
    • 1970-01-01
    • 2018-08-01
    • 2018-05-25
    • 2018-11-15
    • 2021-06-28
    • 2019-02-04
    • 1970-01-01
    相关资源
    最近更新 更多