SignalR / Angular: не удалось загрузить «url». Ответ на предварительный запрос не проходит проверку контроля доступа. - PullRequest
0 голосов
/ 29 августа 2018

Я пытаюсь внедрить простую систему уведомлений, используя 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();
            }
        }
    }

А вот мой класс угловых компонентов:

    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

Спасибо.

1 Ответ

0 голосов
/ 29 августа 2018

Вам также необходимо разрешить учетные данные.

Для этого измените 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();
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...