使用Nodejs和body-parser发布表单数据 [英] Posting form data with Nodejs and body-parser

查看:149
本文介绍了使用Nodejs和body-parser发布表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在已经进行了几次不同的在线尝试,但我的帖子数据和控制台信息一直不确定.console.log(JSON.stringify(req.body))也什么也没有返回.所以我在某个地方出错了. ..

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

推荐答案

尝试添加 Ullencoded选项:

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

这篇关于使用Nodejs和body-parser发布表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆