SignalR / Angular:无法加载“url”。预检请求的响应不会通过访问控制检查。

问题描述 投票:0回答:1

我正在尝试使用SignalR为我的服务器实现一个简单的通知系统,并为我的客户端使用Angular。当我启动我的服务器后运行我的角应用程序时,我收到此错误:

   Failed to load http://localhost:1874/notify/negotiate: Response to
     preflight request doesn't pass access control check: The value of the 'Access-
     Control-Allow-Credentials' header in the response is '' which must be 'true'
     when the request's credentials mode is 'include'. Origin 'http://localhost:4200' 
     is therefore not allowed access. The credentials mode of
     requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

我相信这可能与科尔有关?我的服务器只是发送通知,我的客户端正在显示它们。这就对了。在启动时,我的应用程序无法连接到服务器。这是我的startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

    namespace SignalRHub
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }

            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.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
                {
                    builder
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .WithOrigins("http://localhost:4200");
                }));

                services.AddSignalR();
                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("CorsPolicy");
                app.UseSignalR(routes =>
                {
                    routes.MapHub<NotifyHub>("/notify");
                });

                app.UseMvc();
            }
        }
    }

这是我的Angular Component类:

    import { Component, OnInit } from '@angular/core';
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';

import { Message } from 'primeng/api';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  private _hubConnection: HubConnection;
  msgs: Message[] = [];

  constructor() { }

  ngOnInit(): void {
    this._hubConnection = new HubConnectionBuilder().withUrl('http://localhost:1874/notify').build();
    this._hubConnection
      .start()
      .then(() => console.log('Connection started!'))
      .catch(err => console.log('Error while establishing connection :('));

    this._hubConnection.on('BroadcastMessage', (type: string, payload: string) => {
      this.msgs.push({ severity: type, summary: payload });
    });
  }
}

这是我正在遵循教程的github。

https://github.com/rukshandangalla/Angular5-SignalR-Notifications

谢谢。

asp.net angular signalr
1个回答
0
投票

您还需要允许凭据。

为此,请更改ConfigureServices,并添加.AllowCredentials(),如下所示:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            {
                builder
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials()
                    .WithOrigins("http://localhost:4200");
            }));

            services.AddSignalR();
            services.AddMvc();
        }
© www.soinside.com 2019 - 2024. All rights reserved.