I have an express app set up that has a post route handler (/addpost) which just lets me add the data on to a database. It works like a charm but the window keeps loading. It seems I need to send a response so the browser is not waiting for more data, but all I want is the page to stop loading- I am showing a 'post submitted' text after the submit button is clicked, and don't want to redirect the user to a new page. What should I send back as the response so it stays on the current page (form).
CodePudding user response:
Send the event to the handler function and prevent the page from refreshing on the client side.
onClick={(e) => handleSubmit(e)};
handleSubmit = async (e) => {
e.preventDefault();
//send post request
}
CodePudding user response:
Even if you don't want to send any payload back, you must end the request with res.end()
or res.render(...)
or ...
Whether the user is redirected to another page does not depend on what you send back but on how the browser makes the request:
- If the request is the result of submitting an HTML form, you cannot avoid that the browser navigates, but you could have your server return the same HTML page again.
- If the request is an XMLHttpRequest, for example made via
axios.post
, the browser will not navigate at all but simply receive the response and perhaps update the HTML page based on it. If you don't have any response body, that seems the better option. This is also what Sean Lawton's answer implies where it says "// send post request".