gpt4 book ai didi

azure - 为什么 Azure SignalR 函数在本地主机测试上返回 CORS 错误

转载 作者:行者123 更新时间:2023-12-02 07:35:12 30 4
gpt4 key购买 nike

我正在尝试学习如何使用 Azure functionSignalR 创建无服务器设计。为此,我为 Azure 函数 创建了以下类:

    public static class NotifactionR
{

[FunctionName("negotiate")]
public static SignalRConnectionInfo Negotiate(
[HttpTrigger(AuthorizationLevel.Anonymous)]HttpRequest req,
[SignalRConnectionInfo(HubName = "my-hub")]
SignalRConnectionInfo connectionInfo)
{
// connectionInfo contains an access key token with a name identifier claim set to the authenticated user
return connectionInfo;
}

[FunctionName("NotifactionR")]
public static Task NotifactionR([EventGridTrigger]EventGridEvent eventGridEvent,
[SignalR(HubName = "my-hub")]IAsyncCollector<SignalRMessage> signalRMessages,
ILogger log)
{
log.LogInformation(eventGridEvent.Data.ToString());

return signalRMessages.AddAsync(
new SignalRMessage
{
// the message will only be sent to these user IDs
UserId = "userId1",
Target = "OnNewEvent",
Arguments = new[] { eventGridEvent.Data }
});
}
}

我在 local.settings.json 上使用了以下配置来启用本地测试:

{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureSignalRConnectionString": "Endpoint=https://myservice.service.signalr.net;AccessKey=myaccess-token;Version=1.0;",
"FUNCTIONS_WORKER_RUNTIME": "dotnet"
},
"Host": {
"CORS": "http://localhost:7071",
"CORSCredentials": true
}
}

为了测试这一点,刚刚创建了一个 HTML 文件,其中包含以下脚本:

const connection = new signalR.HubConnectionBuilder()
.withUrl("http://localhost:7071/api", { headers: { 'Access-Control-Allow-Origin': 'http://localhost:7071'}})
.configureLogging(signalR.LogLevel.Trace)
.build();

connection.on('OnNewEvent', ProcessMyEvent);
connection.onclose(() => console.log('disconnected'));
console.log('connecting...');

connection.start()
.then(() => data.ready = true)
.catch(console.error);

当我在 Chrome 上打开 HTML 文件时,我看到以下错误(问题在 Firefox 中也几乎相同):

connecting...
Utils.ts:189 [2019-07-27T16:13:01.573Z] Debug: Starting HubConnection.
Utils.ts:189 [2019-07-27T16:13:01.573Z] Debug: Starting connection with transfer format 'Text'.
Utils.ts:189 [2019-07-27T16:13:01.575Z] Debug: Sending negotiation request: http://localhost:7071/api/negotiate.

SignalRTest.html:1 Access to XMLHttpRequest at 'http://localhost:7071/api/negotiate' from origin 'null' 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.

Utils.ts:182 [2019-07-27T16:13:02.147Z] Warning: Error from HTTP request. 0: .
Utils.ts:179 [2019-07-27T16:13:02.148Z] Error: Failed to complete negotiation with the server: Error
Utils.ts:179 [2019-07-27T16:13:02.148Z] Error: Failed to start the connection: Error
Error
at new HttpError (Errors.ts:20)
at XMLHttpRequest.xhr.onerror (XhrHttpClient.ts:76)

有人知道我在这里做错了什么吗?

更新1

这是我正在使用的 test.html 文件

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://unpkg.com/@aspnet/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d5e444a434c415f6d1c031c0319" rel="noreferrer noopener nofollow">[email protected]</a>/dist/browser/signalr.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="56372e3f3925166678676e7866" rel="noreferrer noopener nofollow">[email protected]</a>/dist/axios.min.js"></script>
<script>
window.apiBaseUrl = 'http://localhost:7071';

function initialize() {
const connection = new signalR.HubConnectionBuilder()
.withUrl(window.apiBaseUrl + "/api", { headers: { 'Access-Control-Allow-Origin': 'http://localhost:7071' } })
.configureLogging(signalR.LogLevel.Trace)
.build();

connection.on('OnNewEvent', ProcessMyEvent);
connection.onclose(() => console.log('disconnected'));
console.log('connecting...');

connection.start({ withCredentials: false })
.then(() => console.log('ready...'))
.catch(console.error);

}
function ProcessMyEvent(vehicle) {
alert("ProcessMyEvent CALLED");
}

initialize();


</script>
</head>
<body>

</body>

</html>

更新2:

我还尝试使用以下命令从命令提示符运行此命令:

c:\Users\Kiran\AppData\Local\AzureFunctionsTools\Releases\2.26.0\cli\func 主机启动 --cors * --pause-on-error

我仍然遇到同样的错误

最佳答案

这有点转移注意力,似乎与我无关。我发现您正在使用 Azure SignalR 服务,连接到该服务的方式与标准 SignalR 不同。

negotiate 函数的行为与 SignalR 服务不同。 negotiate 将返回一些数据以及 accessToken 和 SignalR 服务的 URL ,您需要使用此 URL 进行连接。

我在下面添加了一个示例来说明它应该如何工作。 (我还没有对此进行测试,但希望您能明白)。

function initialize() {
axios.get(window.apiBaseUrl+"/api/negotiate").then(response => {
const options = {
accessTokenFactory: () => response.data.accessToken
}
const socket = new SignalR.HubConnectionBuilder()
.withUrl(response.data.url, options)
.build(SignalR.HttpTransportType.None)

connection.on('OnNewEvent', ProcessMyEvent);
connection.onclose(() => console.log('disconnected'));
console.log('connecting...');

connection.start({ withCredentials: false })
.then(() => console.log('ready...'))
.catch(console.error);
});
}

关于azure - 为什么 Azure SignalR 函数在本地主机测试上返回 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57233956/

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