简体   繁体   English

在React应用中访问API时出错

[英]Error while accessing an api in a react app

Here is the error that I get while accessing an API in my browser . 这是我在浏览器中访问API时遇到的错误。 ERROR: 错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Here is my app.js file.I am basically trying to use random quote generator API.Here is the code. 这是我的app.js文件,我基本上是想使用随机报价生成器API,这是代码。

import React, { Component } from 'react';

import './App.css';
const PATH_BASE='https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en';
class App extends Component {

   getquotes=()=>{
     fetch(`${PATH_BASE}`)
     .then((resp)=>resp.json())
     .then(function(data){
       console.log(data);
     })
     .catch(() => console.log("Can’t access " + PATH_BASE + " response. Blocked by browser?"))


   }
  componentDidMount=()=>{
    this.getquotes()
  }
  render() {
    return (
      <div className="App">
      <h1>Random Quote </h1>
      </div>
    );
  }
}

export default App;

Like epascarello said, the server that hosts the resource needs to have CORS enabled. 就像epascarello所说的那样,承载资源的服务器需要启用CORS。 What you can do on the client side (and probably what you are thinking of) is set the mode of fetch to CORS (although this is the default setting I believe): 您可以在客户端执行的操作(可能是您正在考虑的操作)将获取模式设置为CORS(尽管我相信这是默认设置):

    fetch(request, {mode: 'cors'});

However this still requires the server to enable CORS as well, and allow your domain to request the resource. 但是,这仍然需要服务器也启用CORS,并允许您的域请求资源。

Check out the CORS documentation, and this awesome Udacity video explaining the Same Origin Policy. 查阅CORS文档,以及此精彩的Udacity视频,其中介绍了相同来源策略。

You can also use no-cors mode on the client side, but this will just give you an opaque response 您也可以在客户端使用no-cors模式,但这只会给您不透明的响应

 import React, { Component } from 'react'; import './App.css'; const PATH_BASE='https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en'; class App extends Component { getquotes=()=>{ fetch(`${PATH_BASE}`,{mode: 'no-cors'}) .then((resp)=>resp.json()) .then(function(data){ console.log(data); }) .catch(() => console.log("Can't access " + PATH_BASE + " response. Blocked by browser?")) } componentDidMount=()=>{ this.getquotes() } render() { return ( <div className="App"> <h1>Random Quote </h1> </div> ); } } export default App; 

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

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