1

我的快递应用程序有问题。我正在做的是在车把上有一个表格。我只想根据本教程注册一个用户: 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());

对于路由器:

'使用严格';

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

我使用应用程序但不使用路由器得到它有什么问题?

先感谢您!

4

1 回答 1

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);
于 2017-12-02T04:25:40.040 回答