4

I need to get the selected object using express to console it in app.js

example.html

 <form id="tableForm" action="getJson">
        <select class="example" name="example">
              <option name="" value="0" selected>Select table</option>
              <option name="table1" value="1">Table 1</option>
              <option name="table2" value="2">Table 2</option>
              <option name="table3" value="3">Table 3</option>
        </select>
    </form>

App.js

var express = require('express'),
app = express();

app.use(express.bodyParser());

 app.get('/', function(req, res){
  res.sendfile('views/index.html');
});

app.get('/getJson', function (req, res) {
   console.log(req.body.example);
});

app.listen(3000, function(){
    console.log('Server running at port 3000: http://127.0.0.1:3000')
});

The output of the console is undefined even if I select another object.

1
  • Hi, What's the output in selecting another option (with value 2 for exemple) ? Commented Jan 1, 2019 at 22:12

3 Answers 3

6

You need to add handler for the post method on form submission.

app.js

app.post('/getJson', function (req, res) {
   console.log(req.body.example);
});

example.html

<form method="post" id="tableForm" action="getJson">
  <select class="example" name="example">
      <option name="" value="0" selected>Select table</option>
      <option name="table1" value="1">Table 1</option>
      <option name="table2" value="2">Table 2</option>
      <option name="table3" value="3">Table 3</option>
  </select>
</form>
Sign up to request clarification or add additional context in comments.

Comments

0

try this

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false}));

instead of

app.use(express.bodyParser());

1 Comment

You should explain what the code is doing otherwise it's not a good answer.
0

Here are the mistakes in your code

1)In HTML file , Your form should have a post method

<form method="post" id="tableForm" action="getJson">

(2) That post method should be handled in App.js . The input value given by the user can be collected by req.body.example method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.