首页 > 解决方案 > 从 Angular 应用程序使用 Azure 服务总线发送消息返回 Cors 错误

问题描述

sendLogs() {
    const token = this.getAuthHeader('url', 'syslogsmicroqueue', 'accesskeyhere');
    const options = {
      headers: new HttpHeaders(`Authorization : ${token}`),
      body: {
        log_name: 'sample',
        params:
          { birthdate: 'sample',
            contentCategory: 'sample',
            contentId: 'sample',
            fullName: 'sample',
            ipAddress: 'sample',
            kapamilyaName: 'sample',
            location: 'sample',
            screenName: 'sample',
            userEntitlement: 'sample',
            videoGenre: 'sample',
            videoTitle: 'sample',
            world: ''
          },
        platform: 'web',
        uid: 'sample'
      }
    };

    return this.http.post('https://service-name.servicebus.windows.net/systemlogs_queue/messages', options);
  }

  getAuthHeader(resourceUri: string, keyName: string, key: string) {
    const d = new Date();
    const sinceEpoch = Math.round(d.getTime() / 1000);

    const expiry = (sinceEpoch + 3600);
    const stringToSign = encodeURIComponent(resourceUri) + '\n' + expiry;
    const hash = crypto.HmacSHA256(stringToSign, key);
    const hashInBase64 = crypto.enc.Base64.stringify(hash);

    const sasToken = 'SharedAccessSignature sr=' + encodeURIComponent(resourceUri) + '&sig=' + encodeURIComponent(hashInBase64) + '&se=' + expiry + '&skn=' + keyName;
    console.log(sasToken);

    return sasToken;
  }

我正在使用带有 Azure 服务的 Angular 通用主机,现在我正在尝试在 Azure 服务总线中为每个用户发送系统日志,但它一直返回 CORS 策略错误。我读过这个博客,显然建议在这里做我没有任何访问权限的 Azure 逻辑应用程序。我真正追求的是在不使用 Azure 逻辑应用程序的情况下找到一种方法(我也没有访问权限)。

也许有人在那里尝试并解决了这个问题:)

我尝试安装@azure/service-busazure-sb,我发现它们仅用于服务器端而不是 Angular 应用程序。

从源“ https://localhost:4200 ”访问“ https://name-of-service-bus.servicebus.windows.net/systemlogs_queue/messages ”的 XMLHttpRequest已被 CORS 策略阻止:没有“访问控制” -Allow-Origin' 标头出现在请求的资源上。

标签: angularazureazureservicebusangular-universalangular8

解决方案


根据错误,我会说服务总线不希望您从前端代码调用它们。

将访问密钥放在那里是个坏主意,因为任何人都可以获得密钥。

您可能需要在后端发送消息并从前端调用后端。


推荐阅读