2015-08-15 31 views
1

我在以前的應用程序中已經完成了幾十次,但由於某種原因無法再工作。不知道這是否是版本問題。我已經看過我可以在網上找到的每一個例子,而且沒有任何一個可以工作。不知道我做錯了什麼。相關代碼:無法使用node.js v0.12.7,express 4,body-parser,bootstrap檢索POST數據3

的index.html(從引導網站複製 - 我只加了角色,動作和方法的attrs到窗體標籤)

<html> 

    <head> 
    <!-- Latest compiled and minified CSS --> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> 
    <!-- Optional theme --> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css"> 
    <!-- jQuery --> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
    <!-- Latest compiled and minified JavaScript --> 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> 
    </head> 

    <body> 
    <form role="form" action="/form" method="post"> 
     <div class="form-group"> 
     <label for="exampleInputEmail1">Email address</label> 
     <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email"> 
     </div> 
     <div class="form-group"> 
     <label for="exampleInputPassword1">Password</label> 
     <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password"> 
     </div> 
     <button type="submit" class="btn btn-default">Submit</button> 
    </form> 
    </body> 

</html> 

server.js

var express = require("express"); 
var app = express(); 
var bp = require("body-parser"); 
var path = require("path"); 

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

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

app.post("/form", function(req, res) { 
    console.log(req.body); 
    res.end(); 
}); 

var server = app.listen(4000, function() { 
    var host = server.address().address; 
    var port = server.address().port; 
    console.log('Example app listening at http://%s:%s', host, port); 
}); 

的package.json

{ 
    "name": "test-app", 
    "version": "1.0.0", 
    "description": "", 
    "main": "server.js", 
    "scripts": { 
    "test": "echo \"Error: no test specified\" && exit 1" 
    }, 
    "author": "", 
    "license": "ISC", 
    "dependencies": { 
    "body-parser": "^1.13.3", 
    "express": "^4.13.3", 
    "sqlite3": "^3.0.10" 
    } 
} 

當表單路由被調用時,req.body始終爲{}。儘管過去每次都是這樣的設置。

回答

1

您的表單input元素缺少name屬性,因此不包含在POST請求中。 See this answer

+0

omfg巨大的facepalm,謝謝! – MattL922