Access to XMLHttpRequest from origin 'http://localhost:3000' has been blocked by CORS policy
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.
1 answer
-
answered 2020-11-25 08:15
lala
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 backendhost port
you have specified in your client or react project folder, like so:-client/package.json
orreactFolder/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