简体   繁体   English

React JS 前端中的错误 Access-Control-Allow-Origin

[英]Error Access-Control-Allow-Origin in React JS Frontend

I am Working on a React JS project.我正在研究一个React JS项目。 I have a separate local apache pdf file server.我有一个单独的本地 apache pdf 文件服务器。 I am accessing any pdf file from url eg : ' http://local_server_IPaddress/dirname/sample.pdf '.我正在从 url 访问任何 pdf 文件,例如:' http://local_server_IPaddress/dirname/sample.pdf '。 I am passing this url to display pdf file in react component but I am getting below error.我正在传递此 url 以在 react 组件中显示 pdf 文件,但出现以下错误。 Please tell me how to solve this issue.请告诉我如何解决这个问题。

Ref- https://www.npmjs.com/package/react-pdf code参考 - https://www.npmjs.com/package/react-pdf代码

<Document
      file="http://local_server_IPaddress/dirname/sample.pdf"
      onLoadSuccess={this.onDocumentLoadSuccess}
        >
          <Page pageNumber={pageNumber} />
 </Document>

Error log in browser console浏览器控制台中的错误日志

Access to fetch at ' http://local_server_IPaddress/dirname/sample.pdf ' from origin ' http://localhost:3000 ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.从源“ http://localhost:3000 ”获取“ http://local_server_IPaddress/dirname/sample.pdf ”的访问已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头存在于请求的资源。 If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。

Simple Solution:简单的解决方案:

You can add this URL that allows cors before the actual URL您可以在实际 URL 之前添加此允许 cors 的 URL

file={"https://cors-anywhere.herokuapp.com/" + pdf}

Add proxy field into package.json like this:像这样将proxy字段添加到package.json

"proxy": "http://local_server_IPaddress"

Edit the code, and remove url of server like this:编辑代码,并像这样删除服务器的 url:

<Document
  file="/dirname/sample.pdf"
  onLoadSuccess={this.onDocumentLoadSuccess}
    >
      <Page pageNumber={pageNumber} />
</Document>

It should works on build environment它应该适用于构建环境

See more: https://create-react-app.dev/docs/proxying-api-requests-in-development/查看更多: https : //create-react-app.dev/docs/proxying-api-requests-in-development/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM