I encountered an error message that says:
Access to XMLHttpRequest at 'http://localhost:4000/api/investments' from origin 'http://localhost:5000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
This occurs whenever I attempt to post data to my API using the axios command below:
const [login, setLogin] = useState(
localStorage.getItem('userInfo')
? JSON.parse(localStorage.getItem('userInfo'))
: null
);
const config = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${login.token}`,
},
};
await axios
.post(`${Config.SERVER_ADDRESS}/api/investments`, investmentObj, config)
.then((response) => {
console.log(investmentObj);
notify(`${response.data.name} investimento cadastrado com Sucesso`);
history.push(`/app/investment/${response.data._id}`);
})
.catch((err) => {
console.log(err);
notify(err.response.data, 'danger');
});
I am confused about what steps to take as I have added the following middleware:
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', '*');
res.header('Access-Control-Allow-Credentials', true);
res.header(
'Access-Control-Allow-Headers',
'Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
);
app.use(cors());
next();
});
I suspect that the issue lies with the Authorization in the headers, given that my other API calls are functioning correctly. I would greatly appreciate any assistance with resolving this preflight request dilemma.