Mark Seymour
Mark Seymour

Reputation: 141

Cannot connect to signalr hub from ionic app: Access to XMLHttpRequest ... has been blocked by CORS policy

I'm trying to develop a simple proof of concept for an ionic app sending and receiving signalr messages. I have a very simple signalr web app built in .net 4.5 that is succesfully sending and receiving messages from connected clients within the app host.

I am now trying to connect to this from an ionic app but I get the message

Access to XMLHttpRequest at 'http://localhost:59621/signalr/negotiate' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

when attempting to establish a connection to the signalr hub.

Any assistance is much appreciated.


.Net Code

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);
    }
}

Ionic Code

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));
    }
}

Ionic Info

Ionic:

ionic (Ionic CLI) : 4.0.6

Ionic Framework : ionic-angular 3.9.3

@ionic/app-scripts : 3.2.1

Cordova:

cordova (Cordova CLI) : 8.1.0 Cordova Platforms : none

System:

NodeJS : v8.11.0 (C:\Program Files\nodejs\node.exe) npm : 5.6.0 OS : Windows 10

Environment:

ANDROID_HOME : not set

Upvotes: 2

Views: 3265

Answers (2)

Vinod Gehlot
Vinod Gehlot

Reputation: 117

Your code is fine. issue of CORS related. So You should run as below steps

  1. Create shortcut chrome on desktop and rename no-cors (Whatever name)
  2. Right click on icon and goes to property
  3. Next change target to "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="D:/Chrome" and save.

Then run on this breowser definitely it works. thanks

Upvotes: 0

Mark Seymour
Mark Seymour

Reputation: 141

The problem was that the signalr plugin for ionic required a .Net Core backend. I had been attempting to use a .Net Framework backend.

Upvotes: 1

Related Questions