1

axios. post error.

Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.

I am using the axios, react and redux.

My code is:

  const config = {
    method: 'post',
    url: addActivityUrl,
    data:data,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'application/json',
    },
  };

  return function (dispatch) {
    axios.request(config)
        .then(function(response){
          dispatch({type:ADD_ACTIVITY_SUCCESS,payload:response.data});
        } )
        .catch((error)=> {
          dispatch({type:ADD_ACTIVITY_ERROR,payload:error});
        })
  }
}

I set the breakpoint in the error callback function. When I send a post request,the error above will show me.

I looked for the answer on Stack Overflow. I don't found the answer yet.

I don't know the reason.

jiexishede
  • 2,473
  • 6
  • 38
  • 54
  • Give this a read: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS – fubar Mar 29 '17 at 09:10
  • 1
    You have to add your access-control setting on your server-side. Think about it.. Wouldnt it be quite a security concern if a client could define your server side configurations? – KornholioBeavis Mar 29 '17 at 09:15
  • Possible duplicate of [Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers](http://stackoverflow.com/questions/25727306/request-header-field-access-control-allow-headers-is-not-allowed-by-access-contr) – Mayank Shukla Mar 29 '17 at 09:16

1 Answers1

2

Most you have an issue with custom request headers.

When using custom request header you will get a CORS preflight. This type of request use HTTP OPTIONS and includes Access-Control-Request-Headers listing the headers the client wants to include in the request.

Your client code need to reply to CORS preflight with the appropriate CORS headers. That header needs to contain the same values the Access-Control-Request-Headers.

GibboK
  • 71,848
  • 143
  • 435
  • 658
  • 1
    I delete ` headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json', },. ` The post is OK. – jiexishede Mar 29 '17 at 12:12
  • @jiexishede in this case make sure js and api are on the same domain. Same Domain Policy security – GibboK Mar 29 '17 at 12:13
  • I don't understand it now. I will learn more and more to understand your answer. Thank you very much! – jiexishede Mar 29 '17 at 15:41
  • @jiexishede if you found my answer useful, please do not forget to upvote it :) thanks – GibboK Mar 29 '17 at 16:59
  • 1
    @GibboK, I am having the same issue, which dependencies can solve this error? And I am having a API having "/file.json" in the end. And I am trying to access it using react, I am not getting the list, but if I try by postman and other calls it works. What should I do? – Dhaval Jardosh Oct 10 '17 at 12:22