简体   繁体   中英

Can't retrieve POST data using node.js v0.12.7, express 4, body-parser, bootstrap 3

I've done this dozens of times in previous apps but for some reason can't get it working any more. Not sure if it's a version issue or not. I've looked at every example I could find online and none of it is working. Not sure what I'm doing wrong. Relevant code:

index.html (copied from bootstrap site - I only added the role, action, and method attrs to the form tag)

<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"
  }
}

When the form route gets called, req.body is always {} . This same setup has worked for me every time in the past though.

Your form input elements are missing name attributes and are therefore not being included with the POST request. See this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM