2016-03-16 28 views
0

Iam无法获取html页面。我的nodejs与mongodb连接,但是当iam从html页面获取值时,值不存储在db.Iam中,无法建立从前端到DB在time.help我出去如何将html页面与nodejs连接起来

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

对于使用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()); 
相关问题