【问题标题】:Access to XMLHttpRequest at my api from origin has been blocked by CORS policy [duplicate]CORS 政策已阻止从我的 api 访问 XMLHttpRequest [重复]
【发布时间】:2019-10-18 03:26:03
【问题描述】:

当我从客户端应用程序调用我的 API 方法时,我收到以下错误。我正在使用 .NET Core v2.1.6 和 .NET SDK v2.1.502,我的客户端应用程序正在使用 Angular v5.2.0

在“http://localhost:5000/api/auth/login”访问 XMLHttpRequest 来自原点“http://localhost:4200”已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查: 预检请求不允许重定向。

这是此错误的图片:

我尝试了一种不同的方法,即在 startup.cs 中使用自定义 cors 策略。我可以使用邮递员轻松地从 API 获取数据,但从客户端应用程序中却没有。

我的 Startup.cs 函数:

public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>(x => x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddCors(options => options.AddPolicy("CorsPolicy",
            builder =>
            {
                builder.AllowAnyHeader()
                       .AllowAnyMethod()
                       .SetIsOriginAllowed((host) => true)
                       .AllowCredentials();
            }));
            services.AddScoped<IAuthRepository, AuthRepository>();
            services.AddSignalR();
        }

        // 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();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            //app.UseCors(x => x.WithOrigins("http://localhost:4200/").AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
            app.UseMvc();
            app.UseCors("CorsPolicy");
            
        }

在我的客户端应用程序中使用此服务来验证输入数据:

export class AuthService {
    baseUrl = 'http://localhost:5000/api/auth/';
    userToken: any;
    //
    constructor(private http: Http) { }

    login(model: any) {
        const headers = new Headers({ 'content-type': 'application/json' });
        const options = new RequestOptions({ headers: headers });
        return this.http.post(this.baseUrl + 'login', model, options).map((response: Response) => {
            const user = response.json();
            if (user) {
                localStorage.setItem('token', user.tokenString);
            }
                this.userToken = user.tokenString;
        });
    }
}

【问题讨论】:

  • 从这篇文章中我可以假设这是因为我使用“Content-Type”“Application/json”。那我应该用什么。或者如果我使用它,我需要做什么?
  • 使用浏览器开发工具中的网络窗格检查对 OPTIONS 预检请求的响应。检查 Location 标头,并查看它试图将请求重定向到哪个 URL。然后更改前端 JavaScript 代码中的 URL 以适应 Location 标头的值。它可以像 URL 中的尾部斜杠一样简单——例如,您可能需要将 URL 更改为 http://localhost:5000/api/auth/login/(注意尾部斜杠)而不是 http://localhost:5000/api/auth/login(没有尾部斜杠)您的代码当前的 URL将请求发送到。

标签: angular cors xmlhttprequest asp.net-core-2.0


【解决方案1】:

由于您尝试访问不同域/端口中的端点,您应该为您的角度应用程序configure a proxy。例如:

  1. 在您的项目根文件夹中创建一个文件proxy.conf.json

  2. 示例内容:

    {
      "/api": {
       "target": "http://localhost:3000",
       "secure": false
     }
    }
    
  3. 在你的 angular.json 文件中,添加代理文件配置:

    "architect": {
      "serve": {
        "builder": "@angular-devkit/build-angular:dev-server",
        "options": {
          "browserTarget": "your-application-name:build",
          "proxyConfig": "proxy.conf.json"
        },
    
  4. 如果你的Angular版本是5或更低,没有angular.json文件,仍然可以将proxy作为cli参数引用,例如:

    "start": "ng serve --proxy-config proxy.conf.js"
    

【讨论】:

  • 无法在我的 angular.json(.angular-cli.json) 文件中添加第三个选项。它显示属性“建筑师”是不允许的。请帮忙。
  • 那你肯定用的是旧的 Angular 版本,你仍然可以通过在package.json:"start": "ng serve --proxy-config proxy.conf.js"中更改你的启动命令来引用代理使用
  • 我正在使用 angular cli v1.6.6 angular v5.2.0
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-23
  • 2020-01-05
  • 1970-01-01
  • 2019-12-18
  • 2019-04-28
  • 1970-01-01
  • 2020-05-30
相关资源
最近更新 更多