Wednesday, 7 June 2017

Nodejs : Cannot get route when using add.post

I am a beginner to Node and I am trying to create a multipage application with Mongo(mlab), express and nodejs. I am trying to navigate to a page addUser that takes POST requests. But I keep getting the error

Cannot GET /addUser

when I use add.post on it. However, it does work when I use add.get

Here is app.js

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var path = require('path');
const MongoClient = require('mongodb').MongoClient;

var app = express();
app.set('view engine', 'ejs')
const port = 3000;

MongoClient.connect('mongodb://<user>:<password>@ds111882.mlab.com:11882/serene-brushlands-55292-db', function(err, database) {
    if(err) return console.log(err);
    db = database
    app.listen(port, function() {
    console.log('Server started at port:'+port);
    });
});

var urlencodedParser = bodyParser.urlencoded({ extended:false });

app.get('/', function(req, res) {
    res.sendFile(__dirname+'/index.html');
});

app.post('/addUser', urlencodedParser, function(req, res) {
    res.render('addUser');
    // db.collection('users').save(req.body, function(err, result) {
    //  if (err) return console.log(err);
    //  console.log('saved to database');
    //  res.redirect('/');
    // })
    // console.log(req.body);
});

Not sure what I am doing wrong.

Here is addUser.ejs:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>MY APP</title>
</head>
<body>
    <form action="/addUser" method="POST" >
    <input type="text" placeholder="username" name="username">
    <input type="text" placeholder="specialty" name="specialty">
    <input type="text" placeholder="address" name="address">
    <!-- <input type="file" name="picture"> -->
    <button type="submit">Submit</button>
    </form>
</body>



via Vineet Kaushik

No comments:

Post a Comment