1
votes

I have CORS enabled Web API created using Dotnet Core 2.0. In startup.cs I've enabled CORS as given below

    // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddMvc();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseCors(
                        options => options.WithOrigins("http://localhost/orca").AllowAnyHeader()
            );
            app.UseMvc();
        }
    }
}

I'm calling this web api in Angularjs 5 as given below _Service

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class SdrDataService {
    Url: string = 'http://localhost/ORCA/api/ORCA/asset'

    constructor(private _http: Http) { }

    getdata() {
        let myHeaders = new Headers();
        myHeaders.append('Content-Type', 'application/json');
        let options = new RequestOptions({ headers: myHeaders });
        return this._http.get(this.Url, options)
            .map((response: Response) => response.json())
            .catch(this._errorHandler)
     }

    _errorHandler(error: Response) {
        console.log(error);
        return Observable.throw(error || "Internal server error");
    }
}

I getting an error in console stating : ** Failed to load http://localhost/ORCA/api/ORCA/asset/8Z5324J: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:62001' is therefore not allowed access. The response had HTTP status code 401. **

I'm not sure If I'm missing something to enable CORS for retrieve the data. Any suggestions please?

1

1 Answers

0
votes

For CORS, origins do not include paths. Remove the that path fragment:

 options.WithOrigins("http://localhost:62001")