Posting form data with Nodejs and body-parser

拟墨画扇 提交于 2019-12-10 10:24:28

问题


I have followed a couple of different online attempts at this now and I keep getting undefined for my post data and console.log(JSON.stringify(req.body)) returns nothing also.. So I am going wrong somewhere...

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');
});

回答1:


Try to add Urlencoded option:

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');
});



回答2:


Try to use express-fileupload package you can get data in 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');
});


来源:https://stackoverflow.com/questions/31435539/posting-form-data-with-nodejs-and-body-parser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!