Reputation: 476
I'm new to Angular2. And I'm trying to call POST method to my .net core API.It's working fine with Postman.But when I call it from my angular 2 service it gives an error.
This is my api.service.ts
import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { Headers, Http, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { JwtService } from './jwt.service';
@Injectable()
export class ApiService {
constructor(
private http: Http,
private jwtService: JwtService
) {}
private setHeaders(): Headers {
const headersConfig = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*'
};
if (this.jwtService.getToken()) {
headersConfig['Authorization'] = `Token ${this.jwtService.getToken()}`;
}
return new Headers(headersConfig);
}
post(path: string, body: Object = {}): Observable<any> {
return this.http.post(
`${environment.api_url}${path}`,
JSON.stringify(body),
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
Upvotes: 2
Views: 11089
Reputation: 2083
Link only answers are not going to help people. Here are the relevant codes to fix the problem: In your Startup.cs file, add these lines.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors(o =>
{
o.AddPolicy("CorsPolicy", cp => cp.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials());
}
services.AddMvc()...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseCors("CorsPolicy");
app.UseMvc();
...
}
Upvotes: 0
Reputation: 186
That's a CORS issue. It happens because you are trying to request a resource from a different host. Your API needs to answer those OPTIONS requests properly otherwise the browser is going to block the request.
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
CORS protection isn't implemented in postman so your request works fine there.
Edit: You can also use webpack / angular cli's proxy support if your backend is going to run on the same host in production: https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md
Upvotes: 8
Reputation: 476
Guys thank you for your help. I solved It. As you said error occured because I didn't Implement CORS in my web API. this article was helped me :ASP.NET Core and CORS Gotchas
Upvotes: 3