2

I'm using Node.js and Express to run a webpage on a local server and the webpage collects user information to "register" them as a user.

I'm using body-parser but when I submit the form with user data, nothing prints to my console.

The end project is to have a functional webpage that submits user data to a database using MYSQL. A lot of this code was already in the pre-made Nodejs Express App project.

This is my App.js file:

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

var index = require('./routes/index');
var registration = require('./routes/registration');

var app = express();

var urlencodedParser = bodyParser.urlencoded({ extended: true });

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

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/registration', registration);

app.get('/', function(req, res) {
   res.render('index');
});

app.get('/registration', function(req, res) {
   res.render('registration', {qs: req.query});
});

app.post('/registration', urlencodedParser, function(req, res) {
   console.log(req.body);
   res.render('registration', {qs: req.query});
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
   var err = new Error('Not Found');
   err.status = 404;
   next(err);
});

// 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;

Am I missing something in my html file that allows users to submit data or am I using body-parser incorrectly?

The collection of data takes place in the registration page.

This is a portion of my registration.ejs

<form id="registration-info" method="POST" action="/registration">
    <div class="container">
    <div class="py-5 text-center”>
        <h2>Registration Form</h2>

    <div class="row justify-content-center">

        <div class="col-md-8 order-md-1">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label for="firstName">First name</label>
                    <input type="text" class="form-control" value="" required>
                    <div class="invalid-feedback">
                        Valid first name is required.
                    </div>
                </div>
                <div class="col-md-6 mb-3">
                    <label for="lastName">Last name</label>
                    <input type="text" class="form-control" value="" required>
                    <div class="invalid-feedback">
                        Valid last name is required.
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-5 mb-3">
                    <label for="birthmonth">Birthday</label>
                    <select class="custom-select d-block w-100" required>
                        <option value="">Month</option>
                        <option>January</option>
                        <option>February</option>
                        <option>March</option>
                        <option>April</option>
                        <option>May</option>
                        <option>June</option>
                        <option>July</option>
                        <option>August</option>
                        <option>September</option>
                        <option>October</option>
                        <option>November</option>
                        <option>December</option>
                    </select>
                    <div class="invalid-feedback">
                        Please select a valid month.
                    </div>
                </div>

                <div class="col-md-4 mb-3">
                    <label for="birthday">Day</label>
                    <input type="text" class="form-control" required>
                    <div class="invalid-feedback">
                        Day is required.
                    </div>

                </div>
                <div class="col-md-3 mb-3">
                    <label for="birthyear">Year</label>
                    <input type="text" class="form-control" required>
                    <div class="invalid-feedback">
                        Year is required.
                    </div>
                </div>
            </div>

            <div class="mb-3">
                <label for="password">Password</label>
                <input type="password" class="form-control" >
                <div class="invalid-feedback">
                    Please enter a password.
                </div>
            </div>

            <hr class="mb-4">
            <button class="btn btn-primary btn-lg btn-block" type="submit">Submit</button>
        </div>
    </div>
</div>
</form>

I followed this tutorial: https://www.youtube.com/watch?v=rin7gb9kdpk&t=137s

Solution: Change the order of the app.post and app.get. Also, need to define a name variable in the html file for each piece of info collected from user

1 Answer 1

1

You need to care about the order of your express middleware. If you call res.render a response is send and you are terminating the script. Also care if you don't call in your middleware next() method in your middleware, your script will not go to the next middleware function.

This order is better because now you first log it and then send the response.

app.post('/registration', urlencodedParser, function(req, res) {
   console.log(req.body);
   res.render('registration', {qs: req.query});
});

app.get('/', function(req, res) {
   res.render('index');
});

app.get('/registration', function(req, res) {
   res.render('registration', {qs: req.query});
});

If think this article will help you with writing proper middleware ;)

Example:

This is express routing: the callback will be called if there will be an GET request (app.get if app.post this function would be called by a POST request). Then the callback is executed. The next() indicates to go to the next middleware.

Middleware functions get executed in order and everytime next is called it will got to the next middleware function.

app.get('/', function logger(req,res,next){
  console.log(new Date(), req.method, req.url);
  next();
});

Try to google on express4 routing and middleware. For example:

Docs on express routing

Docs on express middleware

Sign up to request clarification or add additional context in comments.

7 Comments

Oh I thought that you would want to app.get before you app.post. Can you explain how the flow of this program is when you do app.post before the app.get on the registration page? And can you explain how the next() method works? Should I put function(req, res, next) instead? How do I incorporate next into the function?
I've read the links you've posted + other documents and I am not having any luck still. When a user submits the form, app.post receives the info and is supposed to print to console. Shouldn't the data still print to my console before a new page is rendered because the lines execute in order? If I remove the res.render line in app.post and replace it with a next(); then wouldn't it be better to move the app.get(/registration) to right beneath the app.post because once a user submits the form, it should print the data and then go to next() which goes to app.get(/registration) aka a fresh form?
note that app.post is only triggered when you make a post HTTP request to the server. In the case of app.post ('/registration', urlencodedParser, function(req, res) { console.log(req.body); res.render('registration', {qs: req.query}); }); This callback only will get executed when you make a post http request to the /registration domain where / is the root of your website
How are you sending http requests to your server btw?
I thought POST and GET were http requests? This is my first project using nodejs and express so I'm still learning everything but its very confusing
|

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.