DylanB
DylanB

Reputation: 119

How to collect input from a form using node and pug

very new to Node.js and pug, I'm trying to collect form info and store it in a variable to be used elsewhere.

Here's my form:

form(id="cityForm" action="/courses" method="POST")
      input(id="cityInput" type="text" name="cityInput")
      input(type="submit" value="Go!")

I want to collect the value of "cityInput" and store it in a variable. In a js file I have the following code to collect the form info:

window.onload = function(){
    var cityForm = document.getElementById("cityForm");
    var cityName = document.getElementById("cityInput").value;
cityForm.addEventListener("submit", event =>{
    console.log(cityName);
});}

But it doesn't seem to take; I get a 404 error because the 'courses' page doesn't exist yet. What I don't understand is why the console.log doesn't even seem to work, what else do I need in order to grab and store the form information?

Any help would be appreciated.

Upvotes: 0

Views: 1351

Answers (1)

Razin
Razin

Reputation: 109

you need a npm called body-parser, I'm assuming you're using express with node

// in terminal
$ npm install express // install the package
$ npm install body-parser // install the package

// in application
const express = require('express'); //to require the package
const bodyParser = require('body-parser'); //to require the package
const app = express();
app.use(bodyParser.urlencoded({extended: true})); // middleware for parsing bodies
                                                  // from URL. there are
                                                  // more options

app.post('/courses', function(req , res) {
    const cityName = req.body.cityInput; 
// if you log cityName it should be the input from the form which has the name cityInput
});

Upvotes: 1

Related Questions