Angular 5:对预检请求的响应未通过访问控制检查:不存在“Access-Control-Allow-Origin”标头

时间:2018-02-24 02:47:12

标签: angular asp.net-core

我使用Dotnet Core 2.0创建了支持CORS的Web API。在startup.cs中我启用了CORS,如下所示

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

我在Angularjs 5中称这个web api如下所示 的 _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");
    }
}

我在控制台声明中收到错误: **无法加载http://localhost:62001:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“{{3}}”访问。响应具有HTTP状态代码401。 **

我不确定如果我错过了启用CORS来检索数据的东西。 有什么建议吗?

1 个答案:

答案 0 :(得分:0)

对于CORS,起源不包括路径。删除该路径片段:

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