在nodeJS中导出

时间:2016-02-19 17:00:16

标签: javascript mysql node.js express

好的,我有路线:

var express = require('express');
var router = express.Router();
var articles = require('../model/articles.js');

router.get('/all', function(req, res, next) {
  res.json(articles.getAll());
  console.log( "From route: " + articles.getAll());
});
module.exports = router;

,我有模特:

var mysql = require("mysql");
var con = mysql.createConnection({
    host: "localhost",
    user: "rest_news",
    password: "rest_news",
    database: "rest_news"
});
exports.getAll = function () {
    con.query('SELECT * FROM articles', function(err, rows){
        if(err) {
            return err;
        } else {
            console.log("From model:  " + rows);
            return rows;
        }
    });
};

我需要从mysql获取所有文章,我使用该模型文章,方法 getAll()。我在控制台中看到的内容:

From route: undefined
GET /article/all 200 22.802 ms - -
From model:  [object Object],[object Object]
From model:  [object Object],[object Object]

getAll()第二次工作,为什么?

1 个答案:

答案 0 :(得分:0)

使用回调函数:

var mysql = require("mysql");
var con = mysql.createConnection({
    host: "localhost",
    user: "rest_news",
    password: "rest_news",
    database: "rest_news"
});
exports.getAll = function (callbackFunction) {
    con.query('SELECT * FROM articles', callbackFunction);
};

现在在你的路线上做:

var express = require('express');
var router = express.Router();
var articles = require('../model/articles.js');

router.get('/all', function(req, res, next) {
  articles.getAll(function(err, articles){
    if (err) {
        res.status(500).send({message: 'Ups something bad happened!'});
    }else{
        res.json(articles);
    }
  })
});
module.exports = router;

说明:节点使用回调来通知主循环发生了什么。在您的代码中,当您说:

  res.json(articles.getAll());

你实际上发送的是undefined,这就是为什么文章在你的查询函数中存在的原因,因为在获取文章之后执行代码的那部分,并且在你输入模型函数后立即执行res.json(articles.getAll())将查询发送到sql db。