无法在router.post中获取正文但可以使用app.post节点js / express

时间:2017-12-02 04:16:36

标签: node.js express routes express-router

我的快递应用有问题。我正在做的是在汉德尔巴斯有一个表格。我只想根据本教程注册用户: https://www.learn2crack.com/2016/09/android-user-registration-login-node-client.html 但我有点把它调整为网络应用程序。

所以我创建了这样的表单:

<div style="text-align:center">
<form method="POST" action="/registerUser" enctype="application/x-www-form-urlencoded">
  Username: <input type="text" name="name" value=""/><br>
  Email: <input type="text" name="email" value=""/><br>
  Password: <input type="text" name="password" value=""/><br>
  Repeat password: <input type="text" name="repeat_password" value=""></input><br>
  <input type="submit" value="Register!"></input>
</form>
</div

喜欢这个。然后,当我调用一个路由器来处理它的结果(registerUser)时,我得到req.body.name是未定义的(顺便说一句,我检查过,req.query,req.params等等都是未定义的。只是内容没有到达那里到路由器。所以当我这样做时:

router.post('/registerUser', (req, res) => {
    console.log("YO THERE WE GO");
    console.log(req.body);

///..... rest

这不起作用,它是未定义的。但是,如果我在app.js文件夹中执行此操作(路由是单独的,但可以与其他调用一起使用,这是GET),它显然可以使用这个简单的代码:

app.post('/registerUser',function(req,res){
  console.log(req.body);
})

对于应用程序,我有以下内容:

'use strict';

// app.js
const express = require('express');
const session = require('express-session');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
app.use(express.static(path.join(__dirname, 'public')));
const router = require('./routes/router');
app.use(router);
const mongoose = require('mongoose');
const validate = require("validate.js");
const logger = require('morgan');
require('./db');
// const User = mongoose.model('User');
const Item = mongoose.model('Item');
const Pattern = mongoose.model('Pattern');

app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

和路由器:

&#39;使用严格的&#39;;

require('../db');
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Pattern = mongoose.model('Pattern');

我使用app但没有使用路由器,这有什么问题?

提前谢谢!

1 个答案:

答案 0 :(得分:2)

只需输入app.use(bodyParser.json());在路线呼叫之前,如

'use strict';
const mongoose = require('mongoose');
const validate = require("validate.js");
const logger = require('morgan');
require('./db');

// const User = mongoose.model('User');
const Item = mongoose.model('Item');
const Pattern = mongoose.model('Pattern');
const router = require('./routes/router');
// app.js
const express = require('express');
const session = require('express-session');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(router);