In my app I have a list of building on webService and wanna get them with http
with Angular2.
I created a service for that and here is I code wrote for it:
My http service:
import { Injectable, Inject } from '@angular/core';
import { RequestOptionsArgs, Http, Response, RequestOptions, Request, RequestMethod, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { StaticValuesService } from './static-values.service';
import { Building } from '../model/building';
@Injectable()
export class BuildingService {
constructor(private _http: Http, private _values: StaticValuesService) {}
getAllBuildings() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.get(this._values.MainApi + 'api/getbuildings/', options)
.map((response: Response) => response.json());
}
}
And I subscribe in a component with this code:
constructor(private _buildingServices: BuildingService) { }
ngOnInit() {
this._buildingServices.getAllBuildings().subscribe(res => {
console.log(res);
}, error => {
console.log(error);
});
}
After I run the angular server look like the contnet-type
is not set in header of the request! and the result of that is a 404 error on console!
Request content in network chrome:
OPTIONS /api/getbuildings/ HTTP/1.1
Host: nommix-api.azurewebsites.net
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36
Access-Control-Request-Headers: authorization, content-type
Accept: */*
Referer: http://localhost:4200/dashboard/master
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en,en-US;q=0.8,fa;q=0.6
AlexaToolbar-ALX_NS_PH: AlexaToolbar/alx-4.0
Response header:
HTTP/1.1 404 Not Found
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 134
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Set-Cookie: ARRAffinity=12a1bb0d03776b567fa3d04e126a9fa5ad153cba2c87fbc48fc25d775bebd44a;Path=/;Domain=nommix-api.azurewebsites.net
Date: Thu, 02 Feb 2017 11:51:25 GMT
When i tested API with Postman it's work correctly.
Why it doesn't work? and how can I fixed?
Thank you.
assume that you config proxy by this tutorial https://github.com/angular/angular-cli#proxy-to-backend
try to enable CORS in your backend webservice
Access-Control-Allow-Methods: GET, POST, OPTIONS
enable OPTIONS
method in ASP.net app
https://stackoverflow.com/a/21458845/3676586