【问题标题】:React simple REST API using basic authentication使用基本身份验证响应简单的 REST API
【发布时间】:2020-08-05 19:48:12
【问题描述】:

我正在尝试学习如何使用 react 和 rest 并坚持调试或至少检查出了什么问题。我一直在关注一个教程,只是替换了这些值以适合我的示例 rest api 响应,但我得到了空白页。

我的 App.js

 class App extends Component {
      render() {
        return (
          <Products products={this.state.products} />
        )
      }   
      state = {
        products: []
      };

      componentDidMount() {
        var headers = new Headers();
        //test1:test1 is username and password
        headers.append("Content-Type", "application/json");
        headers.append("Authorization", "Basic " + base64.encode("myKey:myPass"));

        fetch('myURL', {headers: headers})
        .then(res => res.json())
        .then((data) => {
          this.setState({ products: data })
        })
        .catch(console.log)
      }

    }

我的产品.js

const Products = ({ products }) => {
  return (
    <div>
      <center><h1>Products List</h1></center>
      {products.map((product) => (
        <div class="card">
          <div class="card-body">
            <h5 class="card-title">{product.title}</h5>
            <h6 class="card-subtitle mb-2 text-muted">{product.price}</h6>
            <p class="card-text">{product.id}</p>
          </div>
        </div>
      ))}
    </div>
  )
};

export default Products

我的示例 json 响应如下所示:

{
    "products": [
        {
            "title": "Cras Selma dress",
            "id": 4985,            
            "price": "1499",
        },
        {
            "title": "Selected Homme Aron suede jacket",
            "id": 4886,
            "price": "2700",

        }
    ]
}

我的第一个猜测是它没有得到正确的响应或没有处理响应。当我使用基本身份验证通过邮递员检查我的 url 时,它都返回了与我发布的 json 响应类似的所有详细信息。

【问题讨论】:

  • 您好,您能否检查一下网络选项卡,看看是否有任何问题,或者通话是否有异常?
  • 哦,很好,所以它说:从源 'localhost:3000' 获取 'about-ourstory.se/wc-api/v3/products' 的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

标签: reactjs rest


【解决方案1】:

我现在知道您遇到了 CORS 问题(在问题的 cmets 中进行了讨论。)。有几种方法可以解决,正确的方法取决于您使用的服务器类型。

如果你使用的是 Node.js

app.use(cors())

就够了,了解更多:https://expressjs.com/en/resources/middleware/cors.html

除此之外,如果您想快速修复,还有一些 Chrome 扩展程序可以帮助您: https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf

因此,问题不在于您的代码,而在于 CORS,您可以在此处了解更多信息 https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

CORS 的另一个快速解决方案是 https://cors-anywhere.herokuapp.com/

你在你的实际 API 之前附加这个,像这样:

const MY_API = 'http://localhost:8080/api/items';

const FULL_API = `https://cors-anywhere.herokuapp.com/${MY_API}`;

axios.get(FULL_API);

尽管如此,我强烈建议您使用谷歌搜索如何解决您正在使用的后端的 CORS 问题。

【讨论】:

  • 谢谢 .. 这让我前进,将阅读来源。
猜你喜欢
  • 1970-01-01
  • 2014-01-26
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
  • 2016-06-08
  • 1970-01-01
  • 2014-02-25
相关资源
最近更新 更多