I've been trying to get a response from a REST API through Axios, I've tried setting the headers up, specifically the Access-Control-Allow-Origin header as stated in the error message, which seems to be the main problem, because even as I insert the required header, it still doesn't acknowledge the header.
axios
.get(url, {
headers: {
"Access-Control-Allow-Origin": "*",
crossDomain: true,
"Content-Type": "text/plain;charset=utf-8",
},
params: {
access_key: API_KEY,
adults: adults,
origin: origin,
destination: destination,
departure: departure,
},
})
.then((res) => {
console.log(res.data);
});
CodePudding user response:
Access-Control-Allow-Origin
must be set on the backend, not the frontend.
CodePudding user response:
CORS is configured on the backend, here's an example with a NodeJS backend and a ReactJS frontend.
//API
import express from "express";
const app = express();
import cors from "cors";
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
cors({
origin: [
"http://localhost:3000",
],
methods: ["GET", "POST", "PUT", "DELETE", "PATCH"],
credentials: true,
})
);
//React Frontend with useEffect and useState
useEffect(() => {
const config = {
headers: { "x-auth-token": token },
};
const fetchData = async () => {
const results = await axios.get("/users/table", config);
setRows(results.data);
};
fetchData();
}, [setRows, state, token]);