axios / axios-docs

Official documentation for the axios HTTP library
MIT License
148 stars 153 forks source link

Axios in React return error CORS with basic auth #103

Open Ramil001 opened 1 year ago

Ramil001 commented 1 year ago

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?

codemaster138 commented 1 year ago

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!

JPLT123 commented 4 weeks ago

I'm this problem too