【发布时间】:2017-01-19 20:45:35
【问题描述】:
我在追踪路由失败的原因时遇到了问题。我是 Sequelize 和 Express 路由的新手。
目标 -
访问 API 端点“/v1/agent/:id”时,我想从 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;
我的 /routes 中的 index.js 文件:
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;
请问有谁愿意再看看这个?
【问题讨论】:
-
我重新创建了错误。问题似乎与在 routes.js 中调用中间件有关。看看你如何在 index.js 中使用路由中间件。仍在研究解决方案,但这可能会有所帮助?
-
我相信这与以下事实有关
-
你在做某事。当我从 db.js 调用它时,我的 sequelize 查询有效,但是当我尝试从 initializeDb (导入语句)引用它时它会丢失
-
从我看到的结果来看,1:您不能调用用作中间件的函数。和 2:当我执行 get: ../:id 时,我似乎无法触发正确的功能
标签: javascript node.js express url-routing sequelize.js