Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my webpage refresh after a NodeJS POST request?

I'm using the express framework with NodeJS. When a client makes a POST request, it pushes some work off to a python script and then returns a JSON object to the client webpage.

My problem is that the client refreshes whenever my POST request completes. I've tested with both the Axios and Fetch http clients. How do I prevent my webpage from refreshing when making a POST request like this?

The server code looks something like:

app.post("/data/", function(req, res) { 

    const spawn = require("child_process").spawn;
    const pythonProcess = spawn('python', ["my_script.py"]);

    pythonProcess.stdout.on('data', (data) => {
          let result = data.toString();
          res.send(JSON.stringify(result));
     });
});

Then I make a request from my React client (using Axios, but Fetch behaves the same way):

axios({
  method: 'post',
  url: `http://localhost:3001/videos/?url=${url}`,
  responseType: 'json',
});

And the client webpage refreshes...

I know React isn't to blame, because nothing is updating the application state. Even if I do nothing with the response from the server, the webpage still refreshes when the POST completes.

Also, there's no form element on my webpage or anything like that, and my button is of type button and not of type submit.

I have a hunch it's something with the way that the python process itself is called, because if I just return a plain JSON object without calling a python subprocess, my client webpage gets the data and doesn't refresh.

like image 306
StupidHTTP Avatar asked Nov 15 '25 19:11

StupidHTTP


2 Answers

I figured it out. Part of my python process was writing files to React's public folder, which apparently causes React to hot-reload.

like image 147
StupidHTTP Avatar answered Nov 18 '25 08:11

StupidHTTP


If you're doing your nodeJS post based on data collected from a <form> -after a user has clicked a button of type=submit, then the issue is that the native HTML behavior of a form's submit button is to do a page refresh.

The way to fix this is -in your form onsubmit, maybe it's onSubmit={handleSubmit} on that handleSubmit function, have it accept an event, call it whatever you want. Then do event.preventDefault() before any other code. Like this:

handleSubmit(e){
   e.preventDefault();
  // the rest of your code, post call ,etc
}
like image 23
SeanMC Avatar answered Nov 18 '25 09:11

SeanMC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!