Search code examples
node.jsexpresspug

Can't retrieve value from input field express pug


I'm confused as to why I can't properly retrieve the value I enter into the input field in the pug code below. I have similar sections in this file that are written pretty much exactly the same and they work fine but for whatever reason I cannot pull the title value from the input field when referencing it from my express code.

index.pug html code:

section(class="get")
h3 Get Data By Title
form(action="/get-data",method="get")
  div(class="input")
    label(for="title") Title
    input(type="text", id="title", name="title")
  button(type="submit") LOAD
div
  if posts
    each val in items
      article(class="item")
        div Title: #{val.title}
        div Content: #{val.content}
        div Author: #{val.author}
        div ID: #{val._id}

And the express code in my index.js file where I try to retrieve the value from input with id="title" and use it to query my database:

router.get('/get-data', function(req, res, next) {
  console.log("get-data")
  var item = {
    title: req.body.title
  };
  console.log(item);
  // Use mongoose to find data from database
  UserData.find(item)
      .then(function(doc) {
        console.log(doc)
        res.render('index', {title:"Movie Database",items: doc});
      }).catch(err => console.log(err));
});

When I view the console output I can see that I retrieve no value, despite the value I entered appearing in my get query url.

0|myapp_node  | get-data
0|myapp_node  | { title: undefined }
0|myapp_node  | []
0|myapp_node  | GET /get-data?title=findme 304 54.497 ms - -
0|myapp_node  | GET /stylesheets/style.css 304 0.382 ms - -

Below is the entire rendered HTML from pug for my file. It includes extra information that may or may not be relevant:

<!DOCTYPE html>
<html>
    <head>
        <title>Movie Database</title>
        <link rel="stylesheet" href="/stylesheets/style.css">
    </head>
    <body>
        <h1>Movie Database</h1>
        <p>Welcome to Movie Database</p>
        <section class="insert">
            <h3>Insert Data</h3>
            <form action="/insert" method="post">
                <div class="input">
                    <label for="title">Title</label>
                    <input type="text" id="title" name="title">
                </div>
                <div class="input">
                    <label for="content">Content</label>
                    <input type="text" id="content" name="content">
                </div>
                <div class="input">
                    <label for="author">Author</label>
                    <input type="text" id="author" name="author">
                </div>
                <button type="submit">INSERT</button>
            </form>
        </section>
        <section class="get">
            <h3>Get Data By Title</h3>
            <form action="/get-data" method="get">
                <div class="input">
                    <label for="title">Title</label>
                    <input type="text" id="title" name="title">
                </div>
                <button type="submit">LOAD</button>
            </form>
            <div></div>
        </section>
        <section class="update">
            <h3>Update Data</h3>
            <form action="/update" method="post">
                <div class="input">
                    <label for="title">Title</label>
                    <input type="text" id="title" name="title">
                </div>
                <div class="input">
                    <label for="id">ID</label>
                    <input type="text" id="id" name="id">
                </div>
                <div class="input">
                    <label for="content">Content</label>
                    <input type="text" id="content" name="content">
                </div>
                <div class="input">
                    <label for="author">Author</label>
                    <input type="text" id="author" name="author">
                </div>
                <button type="submit">UPDATE</button>
            </form>
        </section>
    </body>
</html>

And here is my app.js file:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
// app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;


Solution

  • So the data you're looking for is on the query property of your request object. The way that you know this is that, in your server log, you see:

    GET /get-data?title=findme
    

    When you see a ? following the path, there's a query coming through on the request object. To access those properties, you just tap into req.query.title or req.query.you_prop_name_here.

    Here's a snippet from the express docs to show you how this works a bit more.

    // GET /search?q=tobi+ferret
    req.query.q
    // => "tobi ferret"
    
    // GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse
    req.query.order
    // => "desc"
    
    req.query.shoe.color
    // => "blue"
    
    req.query.shoe.type
    // => "converse"