Angular2 - http://localhost:4200/ being appended with api call why?

╄→尐↘猪︶ㄣ 提交于 2019-12-05 13:15:29

You need to add your protocol for your URL. Otherwise, it's a relative URL:

.post('http://localhost/usmanProject/api/web/v1/users?access-token=n-EJtZiejtz5RSVWe-U14G4kCnPWMKf0', user, { headers: this.headers })

http://localhost:4200/ is the url the page is initially loaded from.

You should either add the full url like

.post('//localhost:4200/usmanProject/api/web/v1/users?access-token=n-EJtZiejtz5RSVWe-U14G4kCnPWMKf0', user, { headers: this.headers })

or

.post('http://localhost:4200/usmanProject/api/web/v1/users?access-token=n-EJtZiejtz5RSVWe-U14G4kCnPWMKf0', user, { headers: this.headers })

or no host part at all

.post('usmanProject/api/web/v1/users?access-token=n-EJtZiejtz5RSVWe-U14G4kCnPWMKf0', user, { headers: this.headers })

Experienced this problem and solved it through separation of concern by creating a app.settings.ts file that will contain the end point to where the api is being served from

export class AppSettings {
   public static get FOLDER_ENDPOINT(): string {
     return 'http://127.0.0.1:8000';
   } 
}

Then create a service and import the app.settings as below

import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import { HttpHeaders } from '@angular/common/http/src/headers';
import { Http, Response, RequestOptions, ResponseContentType } from 
'@angular/http';
import 'rxjs/Rx';
import { AppSettings } from '../app.settings';


@Injectable()
export class FormsubmitService {

constructor(private http: HttpClient) { }

listAll(data: any): Observable<any> {
  return this.http
    .get(`${AppSettings.FOLDER_ENDPOINT}/list-files`);
 }
}

In your app.component.html add a function that triggers the api call

<button (click)="loadData()" class="btn btn-primary pull-right">load data</button>

Then in your app.component.ts you write your method

loadData() {
  this._fbService.listAll('').subscribe(data => {
   console.log('Data returned', data);
  });
}

Your Url should be like url:string ="www.example.com";

It should not be like url:string =" 'www.example.com' ";

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!