简体   繁体   中英

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. 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. What might a componendeDidMiunt with header look like?

   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...


    // 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.

Let's say you have a file in public folder public/data.js . All you have to do is add cors to the route.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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