-1

I'm trying to make an API call using react. My code looks similar to the below one. When I try it, I'm getting an logging error(404-page not found).

componentDidMount() {
        this.setState({loading: true})
        fetch('https://jsonplaceholder.typicode.com/users', {

          headers: new Headers({
             Authorization: "Bearer XXXXXXXXXXXXXXXXXXXXX",
            "Content-Type": "application/json"
          }),
          method: "GET",
          mode: 'no-cors'
        })

Please help me with the issue.

sudha
  • 25
  • 1
  • 7

1 Answers1

0

You have to remove the content-type property. The body of the request is empty, that's why it fails.

W3C - Content-Type Header Field

The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.

UPDATE: If you are using Chrome to test it, please read this thread No 'Access-Control-Allow-Origin' header is present on the requested resource error

class MyApp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
     res : {},
    };
  }
  
  componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/users', {
             headers: new Headers({
             Authorization: "Bearer XXXXXXXXXXXXXXXXXXXXX",
          }),
          method: "GET"
        })
        .then(res => res.json())
        .then(json => this.setState({ res: json}));
 };
 
  render() {
    return (<div> { JSON.stringify(this.state) } </div>);
  };
}

ReactDOM.render(<MyApp />, document.body);
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Joseba
  • 98
  • 2
  • 3
  • I removed it and tried, it did not work got the same issue. – sudha May 10 '18 at 10:32
  • 1
    @sudhach That's because the response has CORS headers and you are sending a no-cors request, remove it too. – Joseba May 10 '18 at 10:50
  • Removed it, got the following error,Failed to load https://jsonplaceholder.typicode.com/users: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.feed: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. – sudha May 10 '18 at 10:58
  • @sudhach I guess that you are using Chrome to test it so read this thread https://stackoverflow.com/questions/28547288/no-access-control-allow-origin-header-is-present-on-the-requested-resource-err/38000615#38000615 – Joseba May 10 '18 at 11:12
  • Thank you. It worked by adding the 'Access-Control-Allow-Origin' chrome extension – sudha May 10 '18 at 11:26