3

我现在已经对此进行了几次不同的在线尝试,并且我的帖子数据一直未定义,并且 console.log(JSON.stringify(req.body)) 也没有返回任何内容。所以我在某个地方出错了...

HTML:

<!DOCTYPE HTML>
<html>
  <head>
    <title>Chat</title>
  </head>
  <body>
    <form action="/" method="post">
      <button>Close</button><br/><br/>
      <label for="username">Your Name: *</label><br/>
      <input id="username" type="text" value="" name="username" autocomplete="off" required="required" /><br/>
    <!--   <label for="email">Email: *</label><br/>
      <input id="email" value="" name="email_address" autocomplete="off" required="required" /><br/> -->
      <label for="phone">Phone:</label><br/>
      <input id="phone" value="" name="phone" autocomplete="off" /><br/>
      <label for="question">Question: </label><br/>
      <textarea id="question" name="question">
      </textarea required="required"><br/><br/>
      <button type="submit">Chat</button>
    </form>
  </body>
</html>

JS:

var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require('body-parser');

app.use(bodyParser.json());

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

app.post('/', function(req, res) {
    var username = req.body.username;
    res.send('<h1>Hello</h1> '+username);
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});
4

2 回答 2

3

尝试添加Urlencoded 选项

var app = require('express')();
var http = require('http').Server(app);
var bodyParser = require('body-parser');

// Add this line below
app.use(bodyParser.urlencoded({ extended: false })) 

app.use(bodyParser.json());

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

app.post('/', function(req, res) {
    var username = req.body.username;
    res.send('<h1>Hello</h1> '+username);
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});
于 2015-07-15T16:25:08.590 回答
3

尝试使用 express-fileupload 包,您可以在 req.body 中获取数据

var app = require('express')();
var http = require('http').Server(app);
const fileUpload = require('express-fileupload')

app.use(fileUpload());

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

app.post('/', function(req, res) {
var username = req.body.username;
res.send('<h1>Hello</h1> '+username);
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});
于 2017-11-06T13:29:11.730 回答