简体   繁体   English

NodeJS请求主体为空

[英]NodeJS Request Body Empty

I'm using node with express@4.13.4 and body-parser@1.13.3. 我使用的节点是express@4.13.4和body-parser@1.13.3。

My jade page has for instance this property: 我的翡翠页面具有以下属性:

input(type='text',class='form-control', placeholder="Username", name='username', id="username")

The JavaScript code looks like this: JavaScript代码如下所示:

var bodyParser = require('body-parser');

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();
var favicon = require('favicon')
app.use(bodyParser.json());

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use( function(req, res, next){
app.locals.pretty = true
  next()
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/create', function(req,res) {
  res.render("create");
});

app.get('/creation', function(req,res) {
  console.log("creation")
  console.log(req.body)
});

The create page is the first opened and there is also the input field username, but the request body is empty in the /creation function. 创建页面是第一个打开的,还有输入字段用户名,但是/ creation函数中的请求正文为空。 Can anyone help ? 有人可以帮忙吗?

You need to submit the form using POST method and alter the function: 您需要使用POST方法提交表单并更改功能:

app.post('/creation', function(req,res) {
  console.log("creation")
  console.log(req.body); // here will show the values of inputs submited
});

More about express routes. 有关快递路线的更多信息。

As we understood body parse will work on the submit of the form or json with POST request. 据我们了解,正文解析将适用于带有POST请求的表单或json的提交。 in this case make sure you are submitting the form correctly, you can see the POST request in firebug or other tool. 在这种情况下,请确保您正确提交了表单,您可以在firebug或其他工具中看到POST请求。 Once its done correctly you will be able to see the body elements by req.body.username 一旦正确完成,您将可以通过req.body.username查看body元素

you can have simple form like. 您可以使用简单的形式,例如。

<form action='post' ..>
  <input name='username' ..>
  <input type='submit' ..>
</form>

Also I seen two times middleware app.use(bodyParser.json()); 我也看过两次中间件app.use(bodyParser.json()); use. 采用。 in case you missed it. 以防你错过了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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