我正在尝试学习如何使用Azure function
和SignalR
创建无服务器设计。为此,我创建了以下类Azure function
:
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 file
包含以下脚本的内容:
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/signalr@1.1.4/dist/browser/signalr.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios@0.18.0/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 host start --cors * --pause-on-error
我仍然得到同样的错误