0

I am a new bee to React. I am creating a small CRUD application. I have a listing of all users. for that, I have an API which is working fine on postman but giving issue when I use that API in my react app. Here is the error that I am getting

Access to XMLHttpRequest at 'http://dummy.restapiexample.com/api/v1/employees' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

But if i change the Url from http://dummy.restapiexample.com/api/v1/employees to https://jsonplaceholder.typicode.com/albums, then works fine.

Here is my code.

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

  componentDidMount() {
    // const token = 'pt7_VZpxd6jOooNILFwO1qEc5lzLifeN';
    let webApiUrl = 'http://dummy.restapiexample.com/api/v1/employees';
    // let webApiUrl = 'https://jsonplaceholder.typicode.com/albums';

    axios.get(webApiUrl, {
      method: "GET",
      mode: "no-cors",
      headers: {
        "Content-Type": "application/json",
        // "Authorization": "Bearer " + token,
        "Access-Control-Allow-Methods": "GET",
        "Access-Control-Allow-Origin": "*",
      },
    })
    .then( res => {
      this.setState({ isLoaded: true, items: res.data})
    })
  }

I have followed these link No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API , Access to XMLHttpRequest has been bloked by CORS policy But still stuck with the issue. How to solve this issue. Any help would be appreciated.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Jane
  • 127
  • 1
  • 4
  • 13
  • you can check this https://stackoverflow.com/a/43881141/5990249 – sharun k k Nov 25 '20 at 07:14
  • CROS policy errors are backend based. The server you are making request to, you need to allow pings to it. If backend is in node.js, use this [NPM CROS Package](https://www.npmjs.com/package/cors) – Neetigya Chahar Nov 25 '20 at 07:27
  • Does this answer your question? [XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header](https://stackoverflow.com/questions/35553500/xmlhttprequest-cannot-load-xxx-no-access-control-allow-origin-header) – Quentin Dec 08 '21 at 15:04

2 Answers2

2

If you use your own backend then, it would be much more easier and focus if you add "proxy": "http://localhost:3000" or whatever your backend host port you have specified in your client or react project folder, like so:-

  • client/package.json or reactFolder/package.json
{
  "name": "projectname",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
  ...}
  "proxy": "http://localhost:5000"
}

Then you can just do:-

await axios.get('/api/products') // straight away use whatever path you've specified
lala
  • 1,309
  • 9
  • 21
0

So I have tried your code snippet using fetch, i was able to get the data. And sometimes i don't get the data i think too many requests issue (429), it's the service issue i think.

Try with fetch let me know if it worked, may be in axios some header issue is the problem.

Here is below snippet code

import "./App.css";
import { useEffect } from "react";

function App() {
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(
          "http://dummy.restapiexample.com/api/v1/employees"
        );
        const data = await response.json();
        console.log(data);
      } catch (error) {
        console.log(error.message);
      }
    };

    fetchData();
  }, []);

  return <div className="App"></div>;
}

export default App;

May be from here you can start it and understand. Ref. I think as mentioned its the cors issue. Its a common issue so in your case you can solve by adding the proxy url infront of the service

Example

axios.get(`https://cors-anywhere.herokuapp.com/http://dummy.restapiexample.com/api/v1/employees`)

I hope this will give you better understanding.

Learner
  • 8,379
  • 7
  • 44
  • 82