axios-docs icon indicating copy to clipboard operation
axios-docs copied to clipboard

Axios in React return error CORS with basic auth

Open Ramil001 opened this issue 2 years ago • 1 comments

I create react app and i have get data from webservices prestashop 1.7

import axios from 'axios';
import logo from './logo.svg';
import './App.css';


function App() {


  const options = {
    method: 'GET',
    url: 'https://woxxxed.itxcxxy.agency/api/products/6',
    params: {output_format: 'JSON'},
    headers: {Authorization: 'Basic XXXXXXXXXXXXXXNVNzlXSlNYNlU4OVRNWVo6'}
  };
  
  axios.request(options).then(function (response) {
    console.log(response.data);
  }).catch(function (error) {
    console.error(error);
  });

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

image

I have result error CORS

In postman all is good image

rapid good image

Why this axios not working in react? Why my code is bad?

Ramil001 avatar Feb 03 '23 12:02 Ramil001

Hi @Ramil001, thanks for reporting your issue.

The error you're seeing is because of a CORS (cross-origin resource sharing) restriction. Browsers supporting CORS (all popular browsers) will block requests if the server doesn't return an appropriate Access-Control-Allow-Origin header.

This is an issue with the way your API is set up; axios is working fine.

Another tip: The way your code is currently set up, the request would be made every single time App is rendered. Instead, your axios call should be inside a useEffect hook.

Hope I could help!

codemaster138 avatar Feb 10 '23 08:02 codemaster138