Bibin Jaimon
Bibin Jaimon

Reputation: 592

How to extract GET form data in Express.js

The following code is my form html:

<form method="get" action="new_name">
  <input  type="name" required="" maxlength="50" name="username" >
  <button  type="submit">Go</button>
</form>

This submit button produce http://localhost:8080/new_name?username=hai

How can I extract the value of username from the url in an Express server?

Upvotes: 1

Views: 4567

Answers (3)

Deep Kakkar
Deep Kakkar

Reputation: 6305

HTML Code:

It will be same as you are having.

<form method="get" action="new_name">
  <input  type="name" required="" maxlength="50" name="username" />
  <button  type="submit">Go</button>
</form>

Node JS Code:

app.get('/new_name', function (req, res) {
    var username = req.query.username;
})

FYI , if you use post method in html form, then you have to use

app.post('/new_name', function (req, res) {
    var username  = req.body.username;
})

Upvotes: 3

David Vicente
David Vicente

Reputation: 3111

app.get('/new_name', function (req, res, next) {
    var receivedUsername = req.query.username;
})

Upvotes: 4

gokcand
gokcand

Reputation: 6836

Try this:

app.get('/new_name', (req, res, next) => {
    const { username } = req.query; // ?username=hai 
    res.json({ username }); // username is equal to 'hai'
});

Upvotes: 3

Related Questions