gpt4 book ai didi

reactjs - 由于 cors 问题无法使 Signal R 工作 - 被 cors 政策阻止

转载 作者:行者123 更新时间:2023-12-04 02:42:47 24 4
gpt4 key购买 nike

我正在将 React 与 Signal R 一起使用

我有一个标准的 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 应用程序中的集线器如下所示
"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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
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.

谁能看到我做错了什么?

最佳答案

经过几个小时的尝试,我终于得到了这个工作

我将把这个问题和我的解决方案一起保留在这里以帮助其他人

首先 - 在 ConfigureServices 中:

  public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddCors();
services.AddSignalR();
}

确保 Cors 在信号 R 之前

然后在配置
        // Make sure the CORS middleware is ahead of SignalR.
app.UseCors(builder =>
{
builder.WithOrigins("http://localhost:3000") //Source
.AllowAnyHeader()
.WithMethods("GET", "POST")
.AllowCredentials();
});

app.UseEndpoints(endpoints =>
{
endpoints.MapHub<MYHubClass>("/myHub");
});

确保 UseCors 在 UseEndpoints 之前

关于reactjs - 由于 cors 问题无法使 Signal R 工作 - 被 cors 政策阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58510508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com