I’m trying to create a simple React website where when I press a button, it sends a GET request to my nodeJS server. I’m using the fetch API to make the GET request. The problem is that when I press the button on the front-end website, it sends multiple GET requests to my node server.
Here is my react code:
import { Stack, Button } from '@mui/material';
import './App.css';
function On(){
fetch("192.168.1.23:5000/on");
}
function App() {
return (
<div className="App">
<div className='App-div'>
<header className="App-header">
<Stack spacing={2}>
<Button onClick={On} size="large" variant='contained'>Send</Button>
</Stack>
</header>
</div>
</div>
);
}
export default App;
Here is my Server code:
const express = require("express");
const app = express();
app.get("/on", (req, res) => {
console.log("Request");
});
app.listen(5000, () => {console.log("Server Started on Port
5000")});
And here is an image of my server’s console after one GET request:
As you’ll notice, it says "request" three times instead of just one. It does this consistently. One button press equals three GET requests.
Any help on this problem would be much appreciated. Thanks!
2
Answers
Your frontend code looks fine to me, but to verify you can check your network tab inside your browser to see if multiple requests are being sent. If not, then this is a problem with your webserver and not your client code.
Edit: Nevermind… your On function should be declared inside your App component. Move it there like this
You can add a submitbtndisabled feature to prevent multiple API calls.
Something like this: