0

I have the following HTML form:

<form method="POST" action="/api/submit_agent">
    <label for="agent_type">Choose an agent model:</label>
    <select name="agent_type">
      <option value="male_agent" selected>Male Agent</option>
      <option value="female_agent">Female Agent</option>
    </select>
    <input id="submit_agent"type="submit" value="Submit">
</form>

and I want to process the form's fields on my nodejs server like so (i'm using express)

app.post("/api/submit_agent", (req, res) => {
  // do stuff
});

but when I submit my form I get redirected to /api/submit_agent. Is there a way to have this processing not reflect in the browser aka without any type of redirection?

136
  • 1,083
  • 1
  • 7
  • 14
  • Did you try using JS: `document.querySelector("form").addEventListener("submit", e => e.preventDefault())`? – ggorlen May 31 '22 at 15:41

1 Answers1

1

It's not an express thing, just apart of how forms operate in HTML.

You can look at this answer which is similar: Prevent redirect after form is submitted

Just make your post request via js instead of a submit action of your form.

Eli Davis
  • 415
  • 5
  • 6
  • This is correct, but this question has been asked many times before and treated much more comprehensively, so the usual approach is to comment and let folks with more rep vote to close it as a duplicate, avoiding extra noise on the site and making it easier for people to find quality information quickly. See [your answer is in another castle](https://meta.stackexchange.com/questions/225370/your-answer-is-in-another-castle-when-is-an-answer-not-an-answer) for more information of why link-based and partial answers are discouraged. Thanks. – ggorlen May 31 '22 at 15:52