Let's say I have a form (written in JSX) being sent to an Express server:
<form id="log-in-form-itself" action="/submit-form" method="post">
<label htmlFor="username" >Username</label>
<input type="text" id="username" name="username" required></input>
<label htmlFor="password">Password</label>
<input type="password" id="password" name="password" required></input>
<button id="log-in-button">Log In</button>
</form>
I know that the form will go to the server using the "/submit-form" route. The route will be processed in Express like so:
app.post("/submit-form", (req, res) => {
//some form processing. Doesn't matter.
res.send("some value");
});
My question is, how do I access the value of "res.send()" in my frontend code? It's not like a normal fetch request where i'd have a response object to use. The post request is embedded in the form itself, so how do I access its response?
Just for clarity, I am using React for the frontend and Express for the backend.
To answer your question:
"Where does "res.send" go when fulfilling a post request from within a default form?"
It goes back to the browser through an HTTP response, which is bascially everything that was generated on the Backend (in your case by Express) and sent through the res.send
command. You cannot dynamically handle this response, unless you are using JS to handle the form request.
Native HTML form submission, means that you are doing an HTTP Post request and getting back some kind of resource from the backend.
"How do I manually access it in the frontend? There is no response object."
You cannot access it 'manually' in the frontend, since a new page will be loaded. The only options for doing something dynamically, is to embed the data in that response page in some form and also embed some JS to act on that data.
One way to hard-code the data that your form submits into the page that comes back from the server, is to use a script
tag with the data in JSON format:
(This is part of the HTML that will be generated by Express.JS using the data it received from the form POST request)
<script type="application/json" id="json-data">
{
"username": "Ada",
"password": "Lovelace"
}
</script>
<script>
const dataEl = document.querySelector("#json-data");
const json = dataEl.textContent;
console.log( JSON.parse(json).username );
console.log( JSON.parse(json).username.toUpperCase() );
</script>
My suggestion is to go with sending a pure JSON response from Express and handle the form submission through JavaScript, as the approach above it's over-complicating matters.