在koa1.2中使用koa-bodyparser中间使取不到post提交的值
发布于 3 年前 作者 qq83387856 5612 次浏览 来自 问答

app.js

//app.js
var app = require('koa')()
    , koa = require('koa-router')()
    , logger = require('koa-logger')
    , json = require('koa-json')
    , views = require('koa-views')
    , onerror = require('koa-onerror')
    , mongoose = require('./config/mongoose.js')
    , bodyParser = require('koa-bodyparser')
    , db = mongoose();

// routers
var index = require('./routes/index');
var users = require('./routes/users');

// global middlewares
app.use(views('views', {
    root: __dirname + '/views',
    default: 'ejs'
}));
app.use(bodyParser());
app.use(json());
app.use(logger());

app.use(function *(next) {
    var start = new Date;
    yield next;
    var ms = new Date - start;
    console.log('%s %s - %s', this.method, this.url, ms);
});

app.use(require('koa-static')(__dirname + '/public'));

// routes definition
koa.use('/', index.routes(), index.allowedMethods());
koa.use('/users', users.routes(), users.allowedMethods());

// mount root routes  
app.use(koa.routes());

app.on('error', function (err, ctx) {
    logger.error('server error', err, ctx);
});

module.exports = app;

new.ejs

// new.ejs
<!DOCTYPE html>
<html>
<head>
    <% include ./../common/header.ejs %>
</head>
<body>
        <form class="form-horizontal" action="/users/create" method="post">
            <div class="form-group">
                <label for="email" class="col-sm-2 control-label">邮箱</label>
                <div class="col-sm-10">
                    <input type="email" class="form-control" id="email" placeholder="邮箱" value="<%= user.email %>">
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" class="btn btn-success">提交</button>
                    <a href="/users" class="btn btn-default">返回</a>
                </div>
            </div>
        </form>
</body>
</html>

router.js

	router.get('/list', list);
	router.get('/new', add);
	function *add(next) {
    yield this.render('/users/new', {
        title: '添加用户',
        user: {
            email: '',
            nickName: '',
            password: '',
            gender: 0,
            phone: 1,
            imgUrl: '',
            address: ''
        }
    });
}

function *save(next) {
    console.log(this.request.body);
    var user = this.request.body;
    user.createTime = new Date;
    user.lastLogin = new Date;
    var id = users.push(user)
    users.id = id - 1;
    this.redirect('/users');
}

出现的问题

在save方法中使用consolo.log打印this.request.body 值是空的。请教一下是什么原因。

3 回复

最近也碰到了类似问题,请问一下这个问题是怎么解决的啊

我也遇到了,我用的是koa2

把你的badyparser中间件放到router调用前面就行了,恍然大悟。。。。。

回到顶部