从 ReactJS 前端连接到 .NET 6.0 和 SignalR 后端时,无法完成与服务器的协商
我正在尝试使用 .NET 6.0 作为后端,使用 ReactJS 作为前端来创建一个简单的 SignalR Web 应用程序。但是,每次运行该项目时,我都会在控制台中收到一条错误,提示无法完成与服务器的协商。 错误信息图片:
我的 Program.cs 文件的相关部分(.NET 6.0 中没有 Startup.cs):
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using SignalR.Hubs;
// SET FALSE TO USE RAZOR PAGES
var useReact = true;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
//.AllowAnyOrigin()
.WithOrigins("http://localhost:32546", "https://localhost:7146");
}));
builder.Services.AddSignalR();
builder.Services.AddControllers();
builder.Services.AddRazorPages();
builder.Services.AddMvc(options =>
{
options.EnableEndpointRouting = false;
});
builder.Services.AddSpaStaticFiles(config =>
{
config.RootPath = "clientapp/build";
});
builder.Services.AddScoped<IChatHub, ChatHub>();
var env = builder.Environment;
var app = builder.Build();
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseWebSockets();
app.MapRazorPages();
if (useReact)
{
app.UseCors();
app.UseSpa(spa =>
{
spa.Options.SourcePath = "clientapp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
app.UseRouting();
app.MapControllers();
app.MapHub<ChatHub>("chathub");
app.UseMvc();
app.Run();
我的 ReactJS 的相关部分code:
import './App.css';
import React, { useState, useEffect } from 'react';
import * as signalR from '@microsoft/signalr';
const connection = new signalR.HubConnectionBuilder()
.configureLogging(signalR.LogLevel.Debug)
.withUrl("chathub")
.build();
export default function App() {
const [messageInput, setMessageInput] = useState("");
const [userInput, setUserInput] = useState("");
const [allMessages, updateAllMessages] = useState([]);
useEffect(() => {
connection.start().then(() => {
console.log("Connected!");
connection.on("SendMessage", (message) => {
updateAllMessages(allMessages.concat(<li>{message}</li>));
});
}).catch((err) => {
return console.error(err.toString());
});
})
const sendMessage = async () =>{
const chat = {
user: userInput,
message: messageInput
};
if(connection.connectionStarted){
try{
await connection.send("SendMessage", chat);
}
catch(e){
console.log(e);
}
}
};
const setUserName = (event) => {
setUserInput(event.target.value);
}
const setMessageBody = (event) => {
setMessageInput(event.target.value);
}
const formatAllMessagesToTable = () => {
return allMessages.map(element => {
return element;
})
}
return(
<div className="main">
<div className="row">
<div className="col-12">
<label htmlFor="input-user">User</label>
<input type="text" id="input-user" onChange={setUserName}/>
</div>
</div>
<div className="row">
<div className="col-12">
<label htmlFor="input-message">Message</label>
<input type="text" id="input-message" onChange={setMessageBody}/>
</div>
</div>
<div className="row">
<div className="col-6">
<button className="btn btn-primary button" onClick={sendMessage}>
Send message
</button>
</div>
</div>
<hr />
<div className="row">
<div className="col-6">
<ul id="messagesList">
{formatAllMessagesToTable()}
</ul>
</div>
</div>
</div>
);
};
我怀疑这与CORS有关。我尝试以各种方式修改Program.cs的CORS部分,但错误仍然存在。在遵循 Microsoft 关于使用 .NET 6.0 设置 SignalR 的教程后,我还设置了一些 razor 页面,并且应用程序可以完美运行。但我想使用 ReactJS 作为我的前端,这就是问题出现的地方。
I am trying to create a simple SignalR web application using .NET 6.0 for my backend, and ReactJS for my frontend. However, every time I run the project, I get an error in my console about how there was failure to complete negotiation with the server.
Image of error message:
Relevant part of my Program.cs file (no Startup.cs in .NET 6.0):
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using SignalR.Hubs;
// SET FALSE TO USE RAZOR PAGES
var useReact = true;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
//.AllowAnyOrigin()
.WithOrigins("http://localhost:32546", "https://localhost:7146");
}));
builder.Services.AddSignalR();
builder.Services.AddControllers();
builder.Services.AddRazorPages();
builder.Services.AddMvc(options =>
{
options.EnableEndpointRouting = false;
});
builder.Services.AddSpaStaticFiles(config =>
{
config.RootPath = "clientapp/build";
});
builder.Services.AddScoped<IChatHub, ChatHub>();
var env = builder.Environment;
var app = builder.Build();
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseWebSockets();
app.MapRazorPages();
if (useReact)
{
app.UseCors();
app.UseSpa(spa =>
{
spa.Options.SourcePath = "clientapp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
app.UseRouting();
app.MapControllers();
app.MapHub<ChatHub>("chathub");
app.UseMvc();
app.Run();
Relevant part of my ReactJS code:
import './App.css';
import React, { useState, useEffect } from 'react';
import * as signalR from '@microsoft/signalr';
const connection = new signalR.HubConnectionBuilder()
.configureLogging(signalR.LogLevel.Debug)
.withUrl("chathub")
.build();
export default function App() {
const [messageInput, setMessageInput] = useState("");
const [userInput, setUserInput] = useState("");
const [allMessages, updateAllMessages] = useState([]);
useEffect(() => {
connection.start().then(() => {
console.log("Connected!");
connection.on("SendMessage", (message) => {
updateAllMessages(allMessages.concat(<li>{message}</li>));
});
}).catch((err) => {
return console.error(err.toString());
});
})
const sendMessage = async () =>{
const chat = {
user: userInput,
message: messageInput
};
if(connection.connectionStarted){
try{
await connection.send("SendMessage", chat);
}
catch(e){
console.log(e);
}
}
};
const setUserName = (event) => {
setUserInput(event.target.value);
}
const setMessageBody = (event) => {
setMessageInput(event.target.value);
}
const formatAllMessagesToTable = () => {
return allMessages.map(element => {
return element;
})
}
return(
<div className="main">
<div className="row">
<div className="col-12">
<label htmlFor="input-user">User</label>
<input type="text" id="input-user" onChange={setUserName}/>
</div>
</div>
<div className="row">
<div className="col-12">
<label htmlFor="input-message">Message</label>
<input type="text" id="input-message" onChange={setMessageBody}/>
</div>
</div>
<div className="row">
<div className="col-6">
<button className="btn btn-primary button" onClick={sendMessage}>
Send message
</button>
</div>
</div>
<hr />
<div className="row">
<div className="col-6">
<ul id="messagesList">
{formatAllMessagesToTable()}
</ul>
</div>
</div>
</div>
);
};
I have suspicions that this is related to CORS. I have tried modifying the CORS part of Program.cs in all kinds of ways, but the error prevails. I also have some razor pages set up, after following Microsofts tutorial on setting up SignalR with .NET 6.0, and with those the application works flawlessly. But I want to use ReactJS for my frontend instead, and this is where the problems arose.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论