如何将html页面与nodejs连接

时间:2016-03-16 15:56:48

标签: node.js mongodb

我无法获取html页面。我的nodejs正在与mongodb连接,但是当我从html页面获取值时,值不存储在db.Iam中,无法一次建立从前端到db的连接。帮助我出

这是我的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>

这是我的login.js代码

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 个答案:

答案 0 :(得分:1)

要使用req.body.username,您需要使用body-parser模块,

  • 安装:npm install body-parser -S

<强>代码

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

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());