0

Iam not able to get the html page.My nodejs is connecting with mongodb but when iam getting values from html page the values are not storing in db.Iam not able establish the connection from frontend to db at a time.help me out

this is my login.html

<html>
<head>
<title>login</title>
</head>
<body>
<form action="/" method="POST">
<center>
User Name: <input type="text" name="username"> <br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

and this is my login.js code

var express = require('express');

     var app = express();

     var mongoose = require('mongoose');

     var url = 'mongodb://localhost:27017/logindb';

     var loginSchema = mongoose.Schema({
        username: String,
        password: String
     });

     mongoose.connect(url);

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

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

        var Book = mongoose.model('book', loginSchema);

        var book1 = new Book({
            username: req.body.username,
            password: req.body.password
        });
        book1.save(function(err) {
            if (err) throw err;
            console.log("Login saved succesfully");
            res.end('success');
        }
        );
     });

     app.listen(8000, function() {
        console.log("Server is running!");
     });

1 Answer 1

1

For using req.body.username you need to use body-parser module,

  • install: npm install body-parser -S

Code:

var express = require('express'),
    app = express(),
    bodyparser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
Sign up to request clarification or add additional context in comments.

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.