I would like to use axios to get JSON from the API server in Heroku.
The following error occurred and I cannot...
The API server side and client side have not been able to isolate the problem…
- Error Contents
No'Access-Control-Allow-Origin' header is present on the requested resource.Origin' http://localhost:3001' is there not allowed access.
Below is a summary of the detailed environment and what you've tried.
Front-end:using axios in React library
backend (API server):Ruby on Rails (located in Heroku)
constapi_url="https://xxx.herokuapp.com/api/v1 "
const config = {
headers:{'Access-Control-Allow-Origin':'*'}
}
export const readRepositories=()=>async dispatch=>{
const response = wait axios.get(api_url,config);
dispatch({type:READ_REPOSITORIES, response});
}
constapi_url="https://xxx.herokuapp.com/api/v1 "
const config = {
headers:{'Access-Control-Allow-Origin':'*'}
}
export const readRepositories=()=>async dispatch=>{
const response = wait axios.get(api_url,config);
dispatch({type:READ_REPOSITORIES, response});
}
Browser security limits scripted communication from one page (localhost:3001) to another site's API server (xxx.herokuapp.com).(Learn more)
To avoid this limitation, you must add "Access-Control-Allow-Origin" to the API server-side response header at another site and specify the domains to allow.(Example: Access-Control-Allow-Origin:*)
Therefore, you must return the Access-Control-Allow-Origin header on the rails side, not on the axios side, which is the client.
If you use rack-cors, the rails can handle CORS, so please consider it.(Reference: https://qiita.com/residenti/items/3a03e5e0268b354284b7)
© 2024 OneMinuteCode. All rights reserved.