Search code examples
angular2-servicesasp.net-core-webapi

Angular 2 Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header


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.

enter image description here

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());
  }

body values enter image description here

.net core API mothod enter image description here


Solution

  • 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