使用 Sequelize 和 Express 的 API 路由错误

Error with API routing with Sequelize and Express

我在查找路由失败的原因时遇到了问题。我是 Sequelize 和 Express 路由的新手。

目标 - 当访问 API 端点 '/v1/agent/:id' 时,我想 return 来自 Sequelize 查询的 JSON 响应。我已经确认查询有效并带回映射到我的 Agent 模型的一行。

当我启动应用程序时,我从 Node.js 收到一个 Router.use() requires middleware function but got a ' + gettype(fn)); 异常。异常来自initializeDb函数,但我不知道为什么。

这是根 index.js:

import http from 'http';
import bodyParser from 'body-parser';
import express from 'express';
import sequelize from 'sequelize';
import config from './config';
import routes from './routes';

let app = express();
app.server = http.createServer(app);

app.use(bodyParser.json({
  limit:config.bodyLimit
}));

app.use('/v1', routes);

app.server.listen(config.port);

console.log('API listening on port ' + app.server.address().port);

export default app;

我的 index.js 文件来自 /routes:

  import express from 'express';
    import config from '../config';
    import initializeDb from '../db';
    import agent from '../controller/agent'
    // handle db configs
    let router = express();

    initializeDb(db => {

      router.use('/agent', agent({config, db}));

    });

    export default router;

我的代理模型控制器:

import sequelize from 'sequelize';
import { Router } from 'express';
import Agent from '../model/agent';


export default({config, db}) => {
  let api = Router();

  //query for the agent
  api.post('/:id', (req, res) => {
    sequelize
      .query(
        "SELECT agentnum AS agentno,fname,lname,agentname AS full_name,[status] FROM my_table WHERE agentnum='" + req.params.id + "'", {model:Agent})
        .then(function(agent) {
          console.log(agent);
          res.json(agent);
        });
  });
}

最后,模型 agents.js

import sequelize from '../db';

let agent = function(sequelize, DataTypes) {
   sequelize.define('agent', {
      agentnum: {
        type: DataTypes.STRING,
        primaryKey: true,
        allowNull: false
      },
      fname : DataTypes.STRING,
      lname : DataTypes.STRING,
      fullname : DataTypes.STRING,
      status : DataTypes.STRING

  }, {
      tableName: 'Base',
      schema: 'Master',
      freezeTableName: true,
      timestamps: false
  });


};


module.exports = agent;

请问有人愿意多看几眼吗?

您必须 return 来自 agent.js 的 api 对象,以便 express.use 在 routes.js 中正常工作。

这与 Sequelize 无关,因此我已将其从我开始工作的示例中删除。看看。

routes.js

import express from 'express';
import agent from './agent';

// handle db configs
let app = express();

app.use('/agent', agent('config','database'));

export default app;

agent.js

import {Router} from 'express';

export default(config, db) => {

  let api = Router();

  api.get('/:id', (req, res, next) => {
    console.log('config', config);
    console.log('db', db);
    res.send('GET');
  });

  api.post('/:id', (req, res, next) => {
    console.log('config', config);
    console.log('db', db);
    res.send('POST');
  });

  return api;
};

控制台日志只是为了让您可以看到传递下来的值。