From my React JS app , I need to fetch data from servers in other domains. However, I am prevented by CORS policy and not able to fetch the data.
Let us assume that my React app is running on localhost:3000 during the development. I want to make get/post call to another server running on http://myserver.com The URL through which I want to fetch the data is http://ext-server.com/data/records?name=xyz
I have installed http-proxy-middleware thru npm and using it in my react app. Created a setupProxy.js file under src folder with below content :
const { createProxyMiddleware} = require("http-proxy-middleware")
module.exports = app => {
app.use(
createProxyMiddleware('/data/records' , {
target:'http://ext-server.com',
changeOrigin: true
})
)
}
On the landing page of my react app (firstpage.js) when http://localhost:3000 is hit , I have added below piece of code to the button event that makes the get call to the http://ext-server.com
getTheData() {
let url = "http://ext-server.com/data/records?name=" + encodeURIComponent(this.state.name);
axios.get(url,
{
headers: {
"Content-Type":"application/json;charset=UTL-8",
"Access-Control-Allow-Origin": "*",
Accept: "application/json",
},
baseURL: 'http://ext-server.com'
}
).then((response) => {
console.log(response["access_token"]);
}).catch(error) => {
console.log("Error: ", error)
}).then(function () {
console.log("always call it")
});
}
In the package.json , I have added :
"proxy": "http://ext-server.com",
"homepage":"http://localhost:3000",
But I am still getting below error: Access to XMLHttpRequest at 'http://ext-server.com/data/records?name= ' from origin 'http://localhost:3000' has been blocked by CORS policy.
Is there anything that I am missing here ? what is the correct way to use this http-proxy-middleware? Any help will be very useful! Thanks
You can use the Chrome extension if you want the solution for local use only.
Allow CORS: Access-Control-Allow-Origin
However, if you want it on the server, there is no solution. If you need to create your proxy server, I can assist you with the code in Node.js.
import express from "express";
import fetch from "node-fetch";
import cors from "cors";
const app = express();
const PORT = 5000;
const GOOGLE_API_KEY = "xxxxxxxxxxxxxxxxxxxxx";
app.use(
cors({
origin: "http://localhost:4200",
methods: ["GET"],
}),
);
app.get("/api/places", async (req, res) => {
const { query } = req.query;
const url = `https://maps.googleapis.com/maps/api/place/autocomplete/json?input=${encodeURIComponent(query)}&key=${GOOGLE_API_KEY}`;
try {
const response = await fetch(url);
const data = await response.json();
if (!response.ok) {
return res
.status(response.status)
.json({
error: data.error_message || "Failed to fetch data from Google API",
});
}
res.json(data);
} catch (err) {
console.error("Error fetching from Google API:", error);
res.status(500).json({ error: "Internal Server Error" });
}
});
app.listen(PORT, () => {
console.log("Server is running on :", PORT);
});