6

the code below is pretty messy so don't judge too much! I am trying to POST a basic user profile into my database, i don't think i am far off but i keep getting a 404.

im pretty knew to all of these technologies so could somebody please enlighten me as to what i have done wrong.

node.js POST method

var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/local';

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('signIn', { title: 'signIn' });
});

router.get('/getData', function(req, res, next){
    mongo.connect(url, function (err, db) {

        assert.equal(null, error);
        var cursor = db.collection('userData').find();
        cursor.forEach(function(doc, err){
            assert.equal(null, err);
            resultArray.push(doc);
        }, function() {
            db.close();
            res.render('index', {items: resultArray});
        } );
    });
});

router.post ('/insert', function(req,res,next) {
    var item = {
        email: req.body.email,
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        password: req.body.password
    };
    mongo.connect(url, function (err, db) {
        assert.equal(null, err);
        db.collection('userData').insertOne(item, function (err, result) {
            assert.equal(null, err);
            console.log('item has been inserted');
            db.close;
        });
    });

    res.redirect('/');
});
module.exports = router;

form HTML

<!DOCTYPE html>
<html lang="en">
<head>


    <title>SignIn Page</title>
    <link rel="stylesheet" type="text/css" href="/stylesheets/signIn.css"/>


</head>

<body>

<div class="background">


<div class="loginFormWrapper">
    <form action="/users/submit" method="POST">
        <div class="loginForm">
            <label for="firstName">First name:</label>
            <input type="text" class="form-control" id="firstName" name="firstName" placeholder="first name">

            <label for="lastName">Last name:</label>
            <input type="text" class="form-control" id="lastName" name="lastName" placeholder="last name">

            <label for="email">Email address:</label>
            <input type="email" class="form-control" name="email" id="email" placeholder="email">

        </div>
        <div class="form-group">
            <label for="pwd">Password:</label>
            <input type="password" class="form-control" name="password" id="password" placeholder="password">
        </div>
        <div class="checkbox">
            <label><input type="checkbox"> Remember me</label>
        </div>
        <button type="submit" class="btn btn-default">Submit</button>

    </form>
    <form action="users" method="GET">
        <button type="submit" class="btn btn-default">get result</button>
    </form>
</div>

</div>


</body>
</html>

App.js

    var express = require('express');

    var path = require('path');
    var favicon = require('serve-favicon');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var validate = require('form-validate');
    var mongoose = require('mongoose');




    var index = require('./routes/index');
    var users = require('./routes/users');
    var About = require('./routes/about');
    var signIn = require('./routes/signIn');
    var contact = require('./routes/contact');


    var app = express();




    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');

    // uncomment after placing your favicon in /public
    //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));
    app.use('/', index);
    app.use('/users', users);
    app.use('/About', About);
    app.use('/signIn', signIn);
    // app.use('/contact', contact);







//catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
 });

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

user.js

var express = require('express');
var app = require("mongoose");
var router = express.Router();


/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;
5
  • What URL are you requesting? Commented Jul 31, 2017 at 13:34
  • var url? that is the default setup for mongodb. in the post and get methods i am connecting to that database through url.... my code is an amalgamation of different tutorials so some var names may be odd! Commented Jul 31, 2017 at 13:38
  • I meant URL like localhost:3000/users/something that kind of URL. You said you are getting 404 but you did not mention the URL address Commented Jul 31, 2017 at 13:40
  • oh sorry, yeah this > localhost:3000/users/submit Commented Jul 31, 2017 at 13:42
  • Post your routes/users.js file Commented Jul 31, 2017 at 13:45

3 Answers 3

5

A quick reminder, the post() method just gets the data from the <form> you specify. For you to be able to get that data you'd have to do something like this.

app.js

const express = require('express)
const mongoose = require('mongoose)

var app = express()

mongoose.connect('mongodb://localhost:"yourPortHere"/"mongoDBhere"')

Now post needs the body parser in order to be able to retrieve the data and sort of "translate it" to JS, for that you need the body parser.

app.use(bodyParser.urlencoded({extended: false})) //Post Body Parser

Now let's get to the post

app.post("/action", (req, res) => {
var userData = {
    username: req.body.username,
    password: req.body.password
}

For the moment userData is going to hold the data you just retrieved from the <form> Remember that action="/YourActionHere is the identifier for the app.post("/YourActionHere") so those two have to match, otherwise you will not get the data.

To save it to MongoDB you first need to create a model of the object you want to store, if MongoDB has a Database named movies with a directory named films on it you first have to create a Model named film since mongoose will save it in the directory films (<- By directory I mean collection)

So: in folder Models you create a model of the object

const mongoose = require('mongoose')
const Schema = mongoose.Schema
var film = new Schema({
title: String,
year: String,
director: String 
 })
module.exports = mongoose.model("movie", movieSchema)

To be able to use that new Schema you have to import it in you app.js with

var Film = require('pathToFilmSchema')

Now in your post you will save userData to that Schema, and mongoose will store it in the collection specified in its .js.

app.post("/action", (req, res) => {
 var userData = {
    title: req.body."name",
    year: req.body."name",
    director: req.body.""
}
new Film(userData)
})

If the structure is the same de Data in that variable will be stored in a Schema, then you just have to call the method .save(), which you can call right after like this

newFil(userData)
.save()

Now mongoose will store a new object with film Schema into the database you have connected at the top. Keep in mind that, if you don't have a collection named film mongoDB will create one collection named films (the plural, always) and store the Schema there.

After saving you can res.redirect() to "/" or render another page, that's up to you.

Sign up to request clarification or add additional context in comments.

Comments

1

You have posted to url users/submit but i don't see any API for users/submit . You have said to use users for /users urls but have you defined the /submit within /users?

You could go through this Routing in expressjs

1 Comment

ill have a read of that, thanks. i think its clear that i dont understand routing very well
0

Inside your app.post function you should have something like this:

let MongoClient = require('mongodb').MongoClient;
let connectionUrl = "mongodb://localhost:27017/";
// or
// let connectionUrl = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";

// creating the message object
let obj = {"text" : "Something"};

console.log("OBJ: " + obj);

MongoClient.connect(connectionUrl, function(err, client) {
    if (err) throw err;
    
    console.log("Connected correctly to server");

    // if database and collection do not exist they are created
    
    var db = client.db('YourDatabase')
    
    db.collection("YourCollection").insertOne(obj, function(err, res) {
        if (err) throw err;
        console.log("1 message inserted");
        client.close();
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.