I have a React client that connects to a server via a k8s service. Locally I have checked everything and it works when the url is localhost and I'm just running the client on port 3000 and the server on port 5000.
When I put this in kubernetes in GKE this will not work so to connect between a client pod on port 3000 and a server pod on port 5000 I need a service.
I am very grateful to for helping me debug my k8s on this question k8s SO question, but we were even execing into a client pod, creating a main.js file that calls fetch at url http://server-cluster-ip-service:5000 and receiving the correct json - and I have since checked again with improved React and server code, and this definitely works, but when I put the url in a fetch request on the client, the fetch request gets:
VM66:1 GET http://server-cluster-ip-service:5000/ net::ERR_NAME_NOT_RESOLVED
The problem has to be React. I am using React Hooks in a create-react-app project. I have a Home component and an EditUser component inside a Pages folder. I'm using React routing with
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
could the routing be messing up the fetch request?
The error displayed on the Network panel is a CORS error
but I'm not sure how to stop this?
client:
import { useState, useEffect } from "react";
import "./editUser.css";
function EditUser() {
const [users, setUsers] = useState([]);
const getAllUsers = async () => {
console.log("GETTING ALL USERS");
fetch("http://server-cluster-ip-service:5000",
{
mode: 'cors',
headers: {
'Access-Control-Allow-Origin':'*'
}
}
)
.then((res) => res)
.then((data) => {
console.log("DATA", data);
setUsers(data);
});
};
useEffect(() => {
getAllUsers();
}, []);
return (
<div className="App">
<h1 data-position="header">Merr k8s testbed</h1>
<section data-position="quotes">
<h2>Console</h2>
<ul>
{users &&
users.map((user) => (
<li>
<h3>{user.id}</h3>
</li>
))}
</ul>
</section>
</div>
);
}
export default EditUser;
server:
const express = require("express");
var cors = require("cors");
const PORT = 5000;
const app = express(); app.use(cors());
app.listen(PORT, function () { console.log("listening on ", PORT); });
app.get("/", (req, res) => {
console.log("PROCESSING GET USERS REQUEST");
const list = [
{ id: 1, firstName: "item1" },
{ id: 2, firstName: "item2" },
{ id: 3, firstName: "item3" },
];
res.send(list);
});