使用Sequelize和Express进行API路由时出错

我有一个问题,追查为什么我的路由失败。 我是Sequelize和Express路由的新手。

目标 – 访问API端点'/ v1 / agent /:id'时,我想从Sequelize查询返回一个JSON响应。 我已经确认查询起作用,并将一行映射到我的Agent模型。

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

这里是根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; 

任何人都愿意把这第二套眼睛在这个?

您必须从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; }; 

控制台日志只是让你可以看到传递的值。