node.js processing a form with Node.js Cloudant DB Web Starter

252 views Asked by At

I am using the Node.js Cloudant DB Web Starter for a simple application that takes form input from a user and inserts it into the Cloudant DB, but I can't get control returned back to the form or another page. I am very new to this, so could very well be a lack of knowledge. When I enter information into the fields and hit submit, the data is captured from the fields and inserted into the cloudant DB, but then the browsers just displays "OK" and does not return to the form. What I want to do is return back to the same page.

**app.js** 

var db = nano.use('contactme');

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.post('/', function(req, res) {
// console.log(req.body);
    res.sendStatus(200);
    res.redirect('http://xyz.mybluemix.net/#top');

var form_name=req.body.name;
var form_email=req.body.email;
var form_message=req.body.message;

 db.insert({"email": form_email,
   "name": form_name,
  "message": form_message}, null, function(err, body) {
  if (!err){
 console.log(body);
  }
 });

 });

**index.html**
<p>If you would like to contact me please use this form below.</p>

<form method="post" action="/"  >   
 <div class="row 50%">
 <div class="6b"><input type="text" name="name" placeholder="Name" /></div>
 <div class="6b"><input type="text" name="email" placeholder="Email" /></div>
 </div>
 <div class="row 50%">
 <div class="12b">
 <textarea name="message" placeholder="Message"></textarea>
 </div>
 </div>
 <div class="row">
 <div class="12b">
 <input type="submit" value="Send Message" />  
 </div>
 </div>
</form>
1

There are 1 answers

0
Gireesh Punathil On
var express = require('express');
var fs = require('fs');

var app = express();

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var index = fs.readFileSync('./index.html');

// primary route which handles get request, when the browser access first time.
app.get('/', function(req, res) {
// provide the form
res.end(index);
});

// form route. Do the db stuff with the form data, and give back the form.
app.post('/', function(req, res) {
 console.log(req.body);
  // do with the db stuff.
 res.end(index);
 });

app.listen(30000);

Hope this helps. Your code has been in between a pseudo code and the real one. So I have kept only bare minimum things to demonstrate re-sending the form to the client.