Skip to content

be_Week3

sjagoori edited this page May 22, 2020 · 3 revisions

✨Week 3

Input

To take input you have to use body-parser to read the body in network packages.

npm i -s body-parser
./index.js
const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

Now that body-parser is available through your express middleware, we can use it. In our HTML file we have a form, the form consists of one of more input elements.

Our form will be a simple text submission by input and submit button.

The express middleware finds these elements by searching for their name attribute so make sure you don't forget adding that. Since we're submitting data, the value of the method attribute is POST, if we were making a request it'd be GET. Our action will be used by the Express middleware to process the data, we'll come back to this later.

./views/page.ejs
<form action="/submit" method="post">
  <label for="submission">enter something:</label>
  <input type="text" name="submission" id="submission">
  <button type="submit">Submit</button>
</form>

The path in we're linking to in the action is the page we're navigating to if it doesn't return any errors in your middleware process. This time around we're using app.post() because we're dealing with a POST method just like defined in the form.

./routes/router.js

app.post('/submit', (req, res) => {
//this is where body-parser comes to play

  let submission = req.body.submission //syntax: req.body.inputNameValue

/*
  Some logic to process the submission
*/

  res.status(200).send("optional message") // use appropriate status code https://httpstatuses.com/
  res.render('page', [{'query': submission}]) // it's also possible to render a page as result.
}
Clone this wiki locally