Hi everyone,
I'm using a React web app with axios and have tried several ways to add a so-called 'Access-Control-Allow-Origin' header in my request, see below my code:
```
import { useState, useEffect, useRef } from 'react';
import axios from 'api/axios';
const API_ACCESS_URL = 'https://oauth.fatsecret.com/connect/token';
const clientID = process.env.REACT_APP_FATSECRET_CLIENT_ID;
const clientSecret = process.env.REACT_APP_FATSECRET_CLIENT_SECRET;
const SearchFoodData = () => {
const [searchInput, setSearchInput] = useState('');
const [errMsg, setErrMsg] = useState('');
const errRef = useRef();
const fetchAPIaccessToken = async () => {
try {
const response = await axios.post(
API_ACCESS_URL,
JSON.stringify({
auth: {
user: clientID,
password: clientSecret,
},
headers: {
// 'Access-Control-Allow-Origin': 'http://localhost:3000/',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'X-Requested-With',
'content-type': 'application/x-www-form-urlencoded',
},
withCredentials: true,
form: {
grant_type: 'client_credentials',
scope: 'premier localization',
},
})
);
console.log(response); // SHOULD BE A COMMENT
console.log(JSON.stringify(response)); // SHOULD BE A COMMENT
console.log(response.data); // SHOULD BE A COMMENT
console.log(response.accessToken); // SHOULD BE A COMMENT
} catch (err) {
if (!err?.response) {
setErrMsg('No Server Response');
} else {
setErrMsg('Registration failed');
}
errRef.current.focus();
}
};
const handleSearchFoodSubmit = (e) => {
e.preventDefault();
fetchAPIaccessToken();
alert(`your input : ${searchInput}`); // SHOULD BE A COMMENT
};
return (
<section className="search-food-data">
<p
ref={errRef}
className={errMsg ? 'errmsg' : 'offscreen'}
aria-live="assertive">
{errMsg}
</p>
<form onSubmit={handleSearchFoodSubmit}>
<label>Rechercher les apports d'un aliment :</label>
<input
type="text"
value={searchInput}
name="search-food-data-input"
onChange={(e) => setSearchInput(e.target.value)}
/>
<button>Rechercher</button>
</form>
</section>
);
};
export default SearchFoodData; ```
However, I keep getting the same error in my browser, which I'm pasting below:
Would anyone be so kind to help with this issue, please?
I read somewhere that creating an endpoint on my server (which is a Rails API app) with CORS enabled that can act as a proxy for my React web app could solve the issue...
Can anyone confirm and maybe if that's not too much to ask, give me some advice about how to set that up?
Many thanks in advance for your time and help!
Best regards,
Nicolas CUBILIER