问题
just start learning angular2
followed the heroes
tutorial. I am making a create request, the URL is perfectly fine, the parameters are fine. But I am still confused why http://localhost:4200/
is being appended with my API
call, and because of that the URL gets totally changed, and the calls failed.please shed some light over this issue. I googled a lot but could find the reason.
My Create Method
create(user: object): Promise<any> {
return this.http
.post('localhost/usmanProject/api/web/v1/users?access-token=n-EJtZiejtz5RSVWe-U14G4kCnPWMKf0', user, { headers: this.headers })
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}
回答1:
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 })
回答2:
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 })
回答3:
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);
});
}
回答4:
Your Url should be like url:string ="www.example.com";
It should not be like url:string =" 'www.example.com' ";
来源:https://stackoverflow.com/questions/46205569/angular2-http-localhost4200-being-appended-with-api-call-why