简体   繁体   English

什么是标头以及如何从 REST API 获取数据?

[英]What are Headers and how to fetch data from REST API?

Whenever I try to fetch data from my REST API using the 'fetch' method in React, I get the 'has been blocked by CORS policy: No 'Access-Control-Allow-Origin' Error.每当我尝试使用 React 中的“获取”方法从我的 REST API 获取数据时,我都会收到“已被 CORS 策略阻止:无‘Access-Control-Allow-Origin’”错误。 I've done from research and found it can be solved with headers?我已经完成研究,发现它可以用标题来解决? The thing is I am new to react and working with API so I'm not quite sure what they are.问题是我是新来的反应和使用 API,所以我不太确定它们是什么。 What might a componendeDidMiunt with header look like?带有标头的 componendeDidMiunt 可能是什么样的?

   constructor(props) {
    super(props)
    this.state = {
      items: [],
      isLoaded: false
    }
  } 
  componentDidMount() {

    fetch('http://localhost:8080/seniorproject/getUserCourses/1')
      .then(res => res.json())
      .then(json => {
          this.setState({
            isLoaded: true,
            items: json
          })
      });
  }

  render() {
    var {items, isLoaded } = this.state;

    if(!isLoaded) {
      return (
        <div>
          ...Loading
        </div>
      )
    } else {
        return (
          <div className="App">
          Data has been loaded..
          </div>
        );
    }
  }
}

It is not React Issue.这不是反应问题。 You have to solve it on back end side.你必须在后端解决它。

Just add headers to the server code.只需将标头添加到服务器代码即可。 I'll assume it is in nodejs...我假设它在 nodejs 中......


    // Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Pass to next layer of middleware
    next();
});

Another simpler way is to install cors package npm install cors This gives you more flexibility.另一种更简单的方法是安装 cors 包npm install cors这为您提供了更大的灵活性。

Let's say you have a file in public folder public/data.js .假设您在公共文件夹public/data.js中有一个文件。 All you have to do is add cors to the route.您所要做的就是将 cors 添加到路由中。

const cors = require('cors');
app.get('/data.json', cors())

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

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