【问题标题】:Cannot connect to signalr hub from ionic app: Access to XMLHttpRequest ... has been blocked by CORS policy无法从 ionic 应用程序连接到信号器集线器:访问 XMLHttpRequest ... 已被 CORS 策略阻止
【发布时间】:2019-08-05 13:00:34
【问题描述】:

我正在尝试为发送和接收信号器消息的离子应用程序开发一个简单的概念证明。我有一个内置于 .net 4.5 的非常简单的 Signalr Web 应用程序,它可以成功地从应用程序主机中连接的客户端发送和接收消息。

我现在正在尝试从 ionic 应用程序连接到此,但我收到了消息

在“http://localhost:59621/signalr/negotiate”访问 XMLHttpRequest 来自原点“http://localhost:8100”已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查: 响应中“Access-Control-Allow-Origin”标头的值必须 当请求的凭据模式为时,不是通配符“*” '包括'。

尝试建立与信号器集线器的连接时。

非常感谢任何帮助。


.Net 代码

Startup.cs

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // Any connection or hub wire up and configuration should go here
        app.Map("/signalr", map =>
        {
            map.UseCors(CorsOptions.AllowAll);
            var hubConfiguration = new HubConfiguration
            {
                EnableDetailedErrors = true,
            };
            map.RunSignalR(hubConfiguration);
        });
    }
}

ChatHub.cs

[HubName("ChatHub")]
public class ChatHub : Hub
{
    public void Send(string name, string message)
    {
        // Call the addNewMessageToPage method to update clients.
        Clients.All.addNewMessageToPage(name, message);
    }
}

离子密码

import { Component } from '@angular/core';
import { NavController, DateTime, AlertController } from 'ionic-angular';
import { HubConnection, HubConnectionBuilder } from '@aspnet/signalr';

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {

    hubConnection: HubConnection;
    name: string;
    message: string;
    messages: string[] = [];

    constructor(public navCtrl: NavController, public alertCtrl: AlertController) {

    }

    ionViewDidLoad() {

    }

    ionViewWillEnter() {
        let alert = this.alertCtrl.create({
            title: 'Demo',
            message: 'What is your name?',
            inputs: [
                {
                    name: 'Name',
                    placeholder: 'Name'
                }
            ],
            buttons: [
                {
                    text: 'Enter',
                    handler: data => {
                        this.name = data.Name;
                    }
                }
            ]
        });

        alert.present();

        this.hubConnection = new HubConnectionBuilder().withUrl('http://localhost:59621/signalr').build();
        this.hubConnection
            .start()
            .then(() => console.log('Connection started!'))
            .catch(err => {
                debugger;
                console.log('Error while establishing connection :(')
            });

        this.hubConnection.on('addNewMessageToPage', (name: string, receivedMessage: string) => {
            const text = `${name}: ${receivedMessage}`;
            this.messages.push(text);
        });
    }

    sendMessage() {
        this.hubConnection
            .invoke('send', this.name, this.message)
            .then(() => this.message = '')
            .catch(err => console.error(err));
    }
}

离子信息

离子:

离子(离子 CLI):4.0.6

离子框架:离子角 3.9.3

@ionic/app-scripts : 3.2.1

科尔多瓦:

科尔多瓦(科尔多瓦 CLI):8.1.0 Cordova 平台:无

系统:

NodeJS : v8.11.0 (C:\Program Files\nodejs\node.exe) npm:5.6.0 操作系统:Windows 10

环境:

ANDROID_HOME:未设置

【问题讨论】:

    标签: asp.net ionic-framework cors signalr ionic4


    【解决方案1】:

    问题在于 ionic 的信号器插件需要 .Net Core 后端。我一直在尝试使用 .Net Framework 后端。

    【讨论】:

    • 你能解释一下你的解决方案吗?我也在尝试从 ionic 连接 SignalR 并遇到相同的问题..
    • 您的后端/api 应用程序是用什么构建的?它是使用 .Net Core 还是标准 .Net Framework 构建的
    【解决方案2】:

    您的代码很好。 CORS 相关问题。所以你应该按照以下步骤运行

    1. 在桌面上创建快捷方式 chrome 并重命名 no-cors(任何名称)
    2. 右键单击图标并转到属性
    3. 接下来将目标更改为 "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="D:/Chrome" 并保存.

    然后在这个浏览器上运行它肯定可以工作。谢谢

    【讨论】:

      猜你喜欢
      • 2019-04-28
      • 2019-12-18
      • 2021-01-14
      • 2021-10-27
      • 2021-10-05
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      相关资源
      最近更新 更多