SignalR/Angular:未能加载"url".对预检请求的响应未通过访问控制检查. [英] SignalR/Angular: Failed to load"url".Response to preflight request doesn't pass access control check.

查看:83
本文介绍了SignalR/Angular:未能加载"url".对预检请求的响应未通过访问控制检查.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用对服务器使用SignalR和对客户端使用Angular来实现一个简单的通知系统.启动服务器后运行我的angular应用程序时,出现以下错误:

I am trying to implement a simple notification system using SignalR for my server, and Angular for my client. When I run my angular application after starting my server, I receive this error:

   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.

我认为这可能与cors有关?我的服务器只是发送通知,而我的客户端正在显示通知.这就对了.就在启动时,我的应用程序无法连接到服务器.这是我的创业公司.

I believe this may have something to do with cors? My server is just sending notifications and my client is displaying them. That is it. Right at the start up, my application is unable to connect to the server. Here is my 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类:

And here is my Angular Component class:

    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.

Here is the github where I am following the tutorial from.

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

谢谢.

推荐答案

您还需要允许凭据.

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

To do so, change ConfigureServices, and add .AllowCredentials() like so:

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

            services.AddSignalR();
            services.AddMvc();
        }

这篇关于SignalR/Angular:未能加载"url".对预检请求的响应未通过访问控制检查.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆