axios-docs
axios-docs copied to clipboard
Axios in React return error CORS with basic auth
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;
I have result error CORS
In postman all is good
rapid good
Why this axios not working in react? Why my code is bad?
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!