Unable to get JSON from API server present in Heroku in axios

Asked 2 years ago, Updated 2 years ago, 115 views

What do you want to hear

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.

environment

Front-end:using axios in React library
backend (API server):Ruby on Rails (located in Heroku)

Tried

  • Change config when doing axios.get

    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});
    }
  • Access the API server directly from your browser
    Successful

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});
}

javascript ruby-on-rails reactjs heroku axios

2022-09-30 11:01

1 Answers

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)


2022-09-30 11:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.