我正在使用React与Signal R。
我有一个托管我的hub的标准Web应用程序。
当我发送消息时,在Web应用程序的网页上所有功能都可以完美运行。
我还有一个托管在端口3000上的React应用程序。
我按照以下方式更改了IIS Express设置。
<httpProtocol>
<customHeaders>
<clear />
<add name="X-Powered-By" value="ASP.NET" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
<redirectHeaders>
<clear />
</redirectHeaders>
</httpProtocol>
我的服务器端启动cors等代码如下:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddCors(options =>
{
options.AddPolicy("cors",
builder =>
{
builder
.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("http://localhost:3000");
});
});
services.AddSignalR();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors("cors");
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chatHub");
endpoints.MapRazorPages();
});
}
在 React 方面,我已经实现了以下内容
import React, { Component } from 'react';
import * as signalR from '@aspnet/signalr';
class Chat extends Component {
constructor(props) {
super(props);
this.state = {
nick: '',
message: '',
messages: [],
hubConnection: null,
};
}
componentDidMount = () => {
const protocol = new signalR.JsonHubProtocol();
const transport = signalR.HttpTransportType.WebSockets;
const options = {
transport,
logMessageContent: true,
logger: signalR.LogLevel.Trace,
};
// create the connection instance
var hubConnection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:44360/chatHub", options)
.withHubProtocol(protocol)
.build();
this.setState({ hubConnection }, () => {
this.state.hubConnection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log('Error while establishing connection :('));
this.state.hubConnection.on('SendMessage', (user, message) => {
const text = `${user}: ${message}`;
const messages = this.state.messages.concat([text]);
console.log('ssss');
this.setState({ messages });
});
});
}
render() {
return (
<div>
<br />
<div>
{this.state.messages.map((message, index) => (
<span style={{display: 'block'}} key={index}> {message} </span>
))}
</div>
</div>
);
}
}
export default Chat;
您可以看到,我已连接到我的服务器应用程序所在的确切端口
日志中显示我已连接成功
但实际上我没有收到任何消息?
下面是我的Web应用程序中的hub:
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;
connection.on("ReceiveMessage", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = user + " says " + msg;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
connection.start().then(function () {
document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
我曾以为我解决了Cors的问题,但当我将网页保持打开一段时间后,我收到了以下错误提示:
Access to XMLHttpRequest at 'http://localhost:44360/chatHub/negotiate' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
有人能看出我做错了什么吗?
(针对技术问题的询问)
'proxy': 'http://localhost:44360'
,然后您就可以在不使用 baseUrl(http://localhost:44360) 的情况下调用请求了。 - Shawn Yap