错误:CORS 策略已阻止从源访问 https://storage.googleapis.com/url 上的 XMLHttpRequest。使用 gcp SignedURl 时有角度

Ayu*_*rma 2 node.js google-cloud-platform angular

我在我的应用程序中使用 Angular 和 NodeJS。现在我将 pdf 文件存储在 gcp 中cloud storage bucket,并通过使用getSignedUrlnodejs 中的方法获取 pdf 文件的 url。

\n

这是我的nodejs代码:

\n
try {\n      let file = await bucket.file(fileName);\n      let url = await file.getSignedUrl({\n        action: "read",\n        expires: dd + "-" + mm + "-" + yyyy\n      });\n      res.send({\n        message: "found url",\n        data: url,\n      });\n    } catch (e) {\n      console.log(e);\n      res.status(400).send({ message: e });\n    }\n
Run Code Online (Sandbox Code Playgroud)\n

现在,在角度方面,我尝试使用SignedUrl从nodejs获得的pdf文件:

\n

角度服务.ts

\n
  getDataOfUrl(url) {\n    let headers = new HttpHeaders();\n    headers.set('Accept', 'application/pdf');\n    this.http.get(url, { headers: headers, responseType: 'blob' as 'json' }).\n    subscribe(data => {\n      console.log(data)\n    }, (err) => {\n      console.log(err)\n    })\n  }\n
Run Code Online (Sandbox Code Playgroud)\n

角度组件.ts

\n
  onFileDownload(filename) {\n    let body = {\n      fileId: filename+".pdf"\n    }\n    this.homepageService.downloadFile(body).subscribe(\n      (data) =>{\n        this.signedUrl = data.data[0];\n        this.homepageService.getDataOfUrl(this.signedUrl)\n        window.open(data.data[0])\n      }, (error) => {\n        console.log(error)\n      }\n    )\n  }\n
Run Code Online (Sandbox Code Playgroud)\n

现在onFileDownload做两份工作:

\n
    \n
  1. 获取signedUrl并在新选项卡中打开pdf文件,以便我们可以下载它(这工作正常)。
  2. \n
  3. 但是我因为这种方法而发布了这个问题this.homepageService.getDataOfUrl(this.signedUrl),当我传递网址以获取某种格式的pdf数据时,以便我可以使用该数据进行进一步使用,例如将pdf转换为图像。
  4. \n
\n

我从中得到错误:

\n

错误:

\n
Access to XMLHttpRequest at 'https://storage.googleapis.com/url' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.\n\nHttpErrorResponse {headers: HttpHeaders, status: 0, statusText: 'Unknown Error', url: 'https://storage.googleapis.com/humana-author-pubsu\xe2\x80\xa6Et3Da%2BkAtV57lVpNuIs6L1%2BkaUKJCHU65rglKLA%3D%3D', ok: false, \xe2\x80\xa6}\nerror: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: 'error', \xe2\x80\xa6}\nheaders: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}\n\n\nGET https://storage.googleapis.com/url net::ERR_FAILED 200\n
Run Code Online (Sandbox Code Playgroud)\n

小智 5

由于安全原因,您的存储桶拒绝来自外部源的访问。在本例中为http://localhost:4200地址。这就是CORS的设计目的。

Google 有一个关于如何为您的存储桶配置 CORS 的指南。您需要对本地主机地址和您计划检索此数据的任何其他网站执行此操作。