Knex NodeJS并插入数据库

Ste*_*own 4 mysql node.js knex.js

我是nodejs的新手并且正在尝试设置API服务器,这是我的第一次尝试.我想使用mysql而不是mongo db.

我的问题是'knex('user').insert({email:req.body.email});' 似乎不想保存到数据库.

            var dbConfig = {
              client: 'mysql',
              connection: {
                host     : 'localhost',
                user     : 'root',
                password : '',
                database : 'db_nodeapi'
              }
            };
            var express = require('express');                       // call express
            var bodyParser = require('body-parser');                // call body-parser
            var knex = require('knex')(dbConfig);                   // set up database connection
            var app = express();                                    // define our app using express
            app.use(bodyParser.urlencoded({ extended: true }));     // configure app to use bodyParser() 
            app.use(bodyParser.json());                             // this will let us get the data from a POST
            var router     = express.Router();                      // get an instance of the express Router
            router.use(function(req, res, next) {                   // middle ware for authentication
                console.log(' -Logging- ');
                next();                                             // continue to next route without stopping
            });
            router.get('/', function(req, res) {                    // listen for a post on root
                res.json({ message: ' -Success- ' });   
            });
            router.route('/user')                                   // set up user route
                .post(function(req, res) {                          // listen for a post on user
                    console.log(' -Post -');                        // report a post
                    knex('user').insert({email: req.body.email});   // insert user into user table
                    res.json({ success: true, message: 'ok' });     // respond back to request
                });
            app.use('/api', router);                                // register routes beginning with /api  
            var port = process.env.PORT || 8080;                    // set server port number
            app.listen(port);                                       // setup listener
            console.log('Magic happens on port ' + port);           // report port number chosen
Run Code Online (Sandbox Code Playgroud)

问题是我无法将knex添加到数据库中!

CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL,
  `email` varchar(255) NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
Run Code Online (Sandbox Code Playgroud)

这是数据库

ngo*_*ire 16

您的代码中的问题是您缺少".then"语句,这会导致代码的实际执行.

   knex('user').insert({email: req.body.email})
      .then( function (result) {
          res.json({ success: true, message: 'ok' });     // respond back to request
       })
Run Code Online (Sandbox Code Playgroud)

这应该工作.由于knex.js的insert函数是一个promise,你需要调用.then()来实际调用它.

  • 是。Knex需要一个.then()来执行。 (2认同)

nov*_*ven 8

已经有人给出了解决方案。我在这里讲为什么添加一个then语句可以解决这个问题。

事实上,那么,catch语句都可以。请参阅 knex 文档(http://knexjs.org/#Interfaces-then),其中提到:

强制当前查询构建器链进入承诺状态。

所以select、update、insert等只是查询语句构建器,你必须使用then或catch将其转换为 promise 状态。

示例如下:

knex('user').insert({email: req.body.email}) //not working
knex('user').insert({email: req.body.email}).then(()=>{}) //working
knex('user').insert({email: req.body.email}).catch(()=>{}) //working

.then(()=>{
    knex('user').insert({email: req.body.email}) //not working
    knex('user').insert({email: req.body.email}).then(()=>{}) //working
    knex('user').insert({email: req.body.email}).catch(()=>{}) //working
    return knex('user').insert({email: req.body.email}) //working
})
Run Code Online (Sandbox Code Playgroud)


Som*_*iks 1

曾经遇到过类似的问题,尝试一下:

//...
router.route('/user').post(function(req, res) {                          
  knex('user').insert({email: req.body.email}).then(function(ret){
    res.json({ success: true, message: 'ok'/*,ret:ret*/});  
  });   
});
//...
Run Code Online (Sandbox Code Playgroud)