500 error for Fetch request; No 'Access-Contro

2019-07-31 19:27发布

问题:

I am building a front-end web app using create-react-app and making a call to the ProPublica API. The fetch call is below:

export const fetchSenators = () => dispatch => {
fetch('https://api.propublica.org/congress/v1/115/senate/members.json', {
    method: 'GET',
    headers: {
      'X-API-Key': process.env.REACT_APP_PROPUBLICA_API_KEY,
      'Access-Control-Request-Headers': '*'
    }
  }).then(response => response.json())
  .then(data => dispatch({ type: FETCH_SENATORS, payload: data.results[0].members }));    
}

I am getting this error:

"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://anaxagoras.herokuapp.com' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. :1 Uncaught (in promise) TypeError: Failed to fetch"

I do need the response data so I can't use {mode: 'no-cors'}. Are there additional headers that I need to include to allow this request to not return a 500 error?

I generally understand what is happening here and why there is a security concern, but if you could give a simple explanation of why this is happening (and hopefully how to fix it) I would be most appreciate. Thanks!

回答1:

I signed up for a ProPublica API key, and successfully implemented a GET fetch request using the following code:

let fetchSenators = () => {
 fetch('https://api.propublica.org/congress/v1/115/senate/members.json', {
  method: 'GET',
  mode: 'CORS',
  headers: {
  'X-API-Key': 'Q82EAnyHuygomXxK2mNDfcHkvOQ17EmsBPvOc1eq'
  }
}).then(response => response.json()) 
  .then(response => {
    renderResults(response.results[0].members)
})}

You can see it working here:

https://codepen.io/BenSmith/pen/xPVyqp

Note that I have stripped the dispatch aspects of your code.

Points to note:

  • As you are making a cross domain call you want to specify CORS mode in the fetch options.
  • You don't need to use the 'Access-Control-Request-Headers' header as setting CORS mode looks handles this aspect of the request.
  • In your code you should use FETCH_SENATORS_SUCCESS so that the action is unambiguous i.e. FETCH_SENATORS implies that the action is getting senator data when in this case it is not, it's returning the results after a successful request.