-1

I am trying to call a POST request in ReactJs using Axios, but getting an error. Code:

const payload =
        {
            device_id: 'ASDACCAS',
            device_type: 'Web',
            device_version: '1.2',
            device_user_id: 'ASDBADKKK1234AS'
        }
        axios({
                  method: 'post',
                  url: 'https://stageapi.myapi.com/v3_2/user/splash',
                  data: payload,
                  headers: {
                  'secret-key': 'mysecretkey',
                  'Content-Type': 'application/json'
              },
              })

But this is giving me error:

Failed to load https://stageapi.myapi.com/v3_2/user/splash: Response for preflight does not have HTTP ok status.

Kindly help me whats wrong here. I am new to ReactJS and moving from mobile app development environment. I have been on this for so long, tried every method for axios POST including by appending formdata to body. Still the same.

EDIT: Also, I am not sure if its something related to CORS. I have installed the the CORS plugin in chrome. Are there any changes that I need to make in API side code? Which is written in php.

  • "I have installed the the CORS plugin in chrome." — This doesn't support preflight requests. – Quentin Sep 03 '18 at 09:07
  • "Are there any changes that I need to make in API side code?" — Yes, you need to respond to the preflgiht request with an OK status (and the right HTTP headers) – Quentin Sep 03 '18 at 09:07
  • Thanks Quentin, it was indeed the issue with API side handling. I showed it to the backend guy and he fixed it. And as mentioned in the link provided by you, we removed the custom headers. Working fine now. – Mayank Pahuja Sep 03 '18 at 12:35

2 Answers2

-1
     axios.post('https://stageapi.myapi.com/v3_2/user/splash', 
      payload,    
      headers: {
                'secret-key': 'mysecretkey',
                'Content-Type': 'application/json'
             }           
    })
    .then((response) => {
        console.log(response.data);
    });
Truong Dang
  • 1,822
  • 10
  • 18
-1

When you want to make a post request, you need to stringify body request like this:

axios({
    method: 'post',
    url: 'https://stageapi.myapi.com/v3_2/user/splash',
    data: JSON.stringify(payload),
    headers: {
        secret-key': 'mysecretkey',
        'Content-Type': 'application/json'
    },
})
Ali Torki
  • 1,610
  • 12
  • 17