2014-01-30 47 views
4

我想與跨域使用SignalR,但我在調用啓動函數時收到錯誤消息。錯誤消息是"Uncaught TypeError: Cannot call method 'start' of undefined "如何使用SignalR與跨域

我使用的代碼 服務器端:

[assembly: OwinStartup(typeof(SignalRChat.Startup))] 

    namespace SignalRChat 
    { 
     public class Startup 
     { 
      public void Configuration(IAppBuilder app) 
      { 
       app.Map("/signalr", map => 
       {    
        map.UseCors(CorsOptions.AllowAll); 
        var hubConfiguration = new HubConfiguration 
        {     
         EnableJSONP = true 
        };    
        map.RunSignalR(hubConfiguration); 
       }); 
      } 
     } 
    } 

客戶端代碼。

<!DOCTYPE html> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
     <title></title> 
     <script src="/Scripts/jquery-1.6.4.min.js"></script> 
     <script src="/Scripts/jquery.signalR-1.1.4.min.js"></script> 
    </head> 
    <body> 
     <div></div> 
     <script type="text/javascript"> 
     var connection = $.connection.hub.url ='http://localhost:9370/signalr';  
     connection.hub.start() 
      .done(function() { 
       alert('Now connected, connection ID=' + connection.id); 
      }); 
     </script> 
     </body> 
     </html> 

回答

7

沒有與您Signalr連接的初始化和啓動的問題,還聲明瞭一個代理引用樞紐。見下面的例子:

<script src="/Scripts/jquery-1.6.4.min.js"></script> 
<script src="/Scripts/jquery.signalR-1.1.4.min.js"></script> 
<script src="http://localhost:9370/signalr/hubs"></script> 

<script type="text/javascript"> 
    $.connection.hub.url ='http://localhost:9370/signalr'; 
    var yourHubProxy = $.connection.YourHubName; 

    //Do something here with yourHubProxy 

    $.connection.hub.start().done(function() { 
     alert('Now connected, connection ID=' + $.connection.hub.id); 
    }); 
</script> 

另一件事,我不知道爲什麼你在你的服務器端和客戶端使用不同版本的SignalR。對我來說,你的服務器端有SignalR 2.x,你的客戶端有SignalR 1.1.4

看看下面的鏈接,這是關於與跨域的SignalR很好的例子。 http://damienbod.wordpress.com/2013/11/01/signalr-messaging-with-console-server-and-client-web-client-wpf-client/

0

@Lin已經回答了這個問題,但是我想告訴一個與CROSS DOMAIN連接有關的重要問題。

大多數時候,你用Google搜索這個問題,我們使用使用本地主機前找到所有的例子:http://localhost:9370

當你只綁定到localhost,因此,如果您嘗試訪問它不會工作其他地址如http://dev-domain:9370/signalr/hubs遠程您將獲得HTTP錯誤400,即請求主機名無效。

爲了綁定機器上的所有地址,我們要使用這樣的 的http:// *:8097

如果有人在這之後發現問題,檢查防火牆請:)