Thursday, 8 June 2017

nodejs app receive data from post and render to html

I'm just starting to use node.js and I can't quite understand few things. So please don't be mean. I tried to search the web without much results.

I want one webpage to go on wait for a post and then render the data received. so far I was have the following app.js

    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();
    app.use(bodyParser.json()); // for parsing application/json
    app.use(bodyParser.urlencoded({ extended: true })); // for parsing 
    application/x-www-form-urlencoded

    app.set('view engine', 'pug');

    app.get('/', function (req, res) {
     res.render('index', {title: 'GET test',message : 'GET test'});
    });

    var data = "";

    app.post("/",function(req, res) {

    console.log(req.method);
    console.log(req.headers);
    console.log(req.url);
    data=req.body
    console.log(data);
    res.render('index', {title: 'POST test',message : 'POST test'});

    });



    app.listen(8081, function () {
      console.log('Example app listening on port 8081!');
    });

in views/index.pug I have

    html
     head
      title = title
     body
      h1 = message

And whenever I trigger curl --data "field=value" http://127.0.0.1:8081/ I can see the post received inside the terminal but I can't understend how to render this data in a page.



via user32185

No comments:

Post a Comment