【问题标题】:Why is there a Cross Origin Error When Declaring Link In React为什么在 React 中声明链接时会出现跨域错误
【发布时间】:2023-03-08 07:40:02
【问题描述】:

感谢您的宝贵时间。我无法让这个链接在反应中工作。我已经使用了 BrowserRouter 并向路由器传递了一个路径和一个组件。但是我仍然得到一个跨源错误和帮助会很棒。这是代码

    class Products extends React.Component {
  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="col-4">
            <div className="card">
              <img
                className="card-img-top"
                src="/images/pathToYourImage.png"
                alt="Card cap"
              />
              <div className="card-body">
                <h4 className="card-title">Card title</h4>
                <p className="card-text">
                  Some quick example text to build on the card title and make up
                  the bulk of the card's content.
                </p>
                <Link to="/">
                <div className="btn btn-primary">
                  Go somewhere
                </div>
                </Link>
              </div>
            </div>
          </div>
          <div className="col-4">Product Two</div>
          <div className="col-4">Product Three</div>
        </div>
      </div>
    );
  }
}
export default Products;

【问题讨论】:

  • 请发布您遇到的确切错误。

标签: reactjs jsx


【解决方案1】:

没有理由包含 Route 或 BrowserRouter &lt;Link to="/"&gt;&lt;div className="btn btn-outline-primary"&gt;Go Somewhere&lt;/div&gt;&lt;/Link&gt; 检查缩进后工作正常

【讨论】:

    【解决方案2】:

    出于安全原因,已禁用跨源资源共享 (cors),您需要手动启用它。 我使用一个名为 cors 的包作为基于 express 的后端。

    第 1 步

    npm install cors
    

    第 2 步

    const cors = require('cors')
    

    最后一步

    app.use(cors())
    

    这将为所有路由启用CORS。您还可以为单个路由启用。查看github上的文档

    【讨论】:

    • 有用的信息,但这不是引用应用程序之外的资源
    • 据我所知,CORS 是一个后端错误,而不是前端。
    • 是的,与前端相比,它与后端相关的问题更多,正如我提到的,该示例是针对基于快递的后端应用程序,即您可能希望像这样启用您的后端。另外,我特意举了这个例子来帮助可能第一次遇到这个错误的人理解它的含义等等。
    猜你喜欢
    • 2019-08-24
    • 1970-01-01
    • 2018-09-15
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多