Koa.js Tutorial to Get Form Fields Data in Pug Template Using Multipart and Body Parser Middleware

Thanks for reading my article first. Koa.js Tutorial to Get Form Fields Data in Pug Template Using Multipart and Body Parser Middleware We are going to learn more about this in this article. Let’s go into the article

Koa.js Tutorial to Get Form Fields Data in Pug Template Using Multipart and Body Parser Middleware

Koa.js Tutorial to Get Form Fields Data in Pug Template Using Multipart and Body Parser Middleware

html
   head
      title Form Tester
   body
      form(action = "/", method = "POST")
         div
            label(for = "say") Say: 
            input(name = "say" value = "Hi")
         br
         div
            label(for = "to") To: 
            input(name = "to" value = "Koa form")
         br
         button(type = "submit") Send my greetings
var koa = require('koa');
var router = require('koa-router');
var bodyParser = require('koa-body');
var app = koa();

//Set up Pug
var Pug = require('koa-pug');
var pug = new Pug({
   viewPath: './views',
   basedir: './views',
   app: app //Equivalent to app.use(pug)
});

//Set up body parsing middleware
app.use(bodyParser({
   formidable:{uploadDir: './uploads'},
   multipart: true,
   urlencoded: true
}));

_.get('/', renderForm);
_.post('/', handleForm);

function * renderForm(){
   this.render('form');
}
function *handleForm(){
   console.log(this.request.body);
   console.log(this.req.body);
   this.body = this.request.body; //This is where the parsed request is stored
}

app.use(_.routes()); 
app.listen(3000);

Read Also: Koa.js Tutorial to Redirect to External URL (404 Error) Using Koa-router Library in Browser

Final Words

Koa.js Tutorial to Get Form Fields Data in Pug Template Using Multipart and Body Parser Middleware We hope this article solves all your doubts. If in doubt let me know.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment