在 angular 应用中使用 SignalR Core 时出现 CORS 错误
CORS error when using SignalR Core in angular app
在 CORS 配置中,我允许使用 OPTIONS 方法,但是当我发送请求时,抛出错误
OPTIONS http://x.x.x.x:port/function 405 (Method Not Allowed)
我在ConfigureServices方法中的CORS策略Startup.cs如下:
services.AddCors(options =>
{
options.AddPolicy("AllowAny", x =>
{
x.AllowAnyOrigin()
.AllowAnyHeader()
.WithMethods("POST", "OPTIONS");
});
});
并且使用如下:
app.UseCors("AllowAny");
中心代码:
public async Task SendMessage(string user, string message) {
string outputMessage = SensorsControl.controlSensors(message.ToString());
await Clients.All.SendAsync("ReceiveMessage", user, outputMessage);
}
angular 中的 SignalR 代码:
this._hubConnection = new HubConnection('http://x.x.x.x:port/function');
this._hubConnection.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log('Error while establishing connection'));
this._hubConnection.on('ReceiveMessage', (user: string, outputMessage: string) =>
{
const text = ${user}: ${outputMessage}; this.messages.push(text);
});
我解决了伙计们:D 问题是我的 angular 应用程序托管在本应是我的 IPv4 IP 的本地主机上,但它变成了 SignalR 无法理解的 127.0.0.1服务器。在没有任何变化的情况下,我使用 ng serve --host 0.0.0.0 服务 angular,然后使用我的 IPv4 IP 连接,作为魅力:D 谢谢你的帮助!干杯!!
在 CORS 配置中,我允许使用 OPTIONS 方法,但是当我发送请求时,抛出错误
OPTIONS http://x.x.x.x:port/function 405 (Method Not Allowed)
我在ConfigureServices方法中的CORS策略Startup.cs如下:
services.AddCors(options =>
{
options.AddPolicy("AllowAny", x =>
{
x.AllowAnyOrigin()
.AllowAnyHeader()
.WithMethods("POST", "OPTIONS");
});
});
并且使用如下:
app.UseCors("AllowAny");
中心代码:
public async Task SendMessage(string user, string message) {
string outputMessage = SensorsControl.controlSensors(message.ToString());
await Clients.All.SendAsync("ReceiveMessage", user, outputMessage);
}
angular 中的 SignalR 代码:
this._hubConnection = new HubConnection('http://x.x.x.x:port/function');
this._hubConnection.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log('Error while establishing connection'));
this._hubConnection.on('ReceiveMessage', (user: string, outputMessage: string) =>
{
const text = ${user}: ${outputMessage}; this.messages.push(text);
});
我解决了伙计们:D 问题是我的 angular 应用程序托管在本应是我的 IPv4 IP 的本地主机上,但它变成了 SignalR 无法理解的 127.0.0.1服务器。在没有任何变化的情况下,我使用 ng serve --host 0.0.0.0 服务 angular,然后使用我的 IPv4 IP 连接,作为魅力:D 谢谢你的帮助!干杯!!