我在index.js中有这个代码
...
import userRoutes from './src/routes/userRoutes';
import invoicesRoutes from './src/routes/invoicesRoutes';
import authMiddleware from "./src/middlewares/authMiddleware";
...
const app = express();
...
app.use('/user',authMiddleware,userRoutes(app));
app.use('/invoices',invoicesRoutes(app));
我的authmiddleware
const authMiddleware = (req,res,next) => {
if (req.headers && req.headers.authorization && req.headers.authorization.split(' ')[0] === 'JWT') {
console.log(req.headers.authorization.split(' ')[0]);
next();
} else {
console.log('else');
next();
}
};
export default authMiddleware;
和我的一条路线:
import { register,login } from '../controllers/authController';
const userRoutes = (app) => {
app.route('/user/signup')
.post(register);
app.route('/user/login')
.post(login);
};
export default userRoutes;
我收到一个错误:
throw new TypeError(‘Router.use() requires a middleware function but
got a ‘ + gettype(fn))
^TypeError: Router.use() requires a middleware function but got a
undefined
怎么了?
最佳答案
您将路由初始化作为中间件功能传递
app.use(‘/ user’,userRoutes(app));
原文链接:https://www.f2er.com/js/429233.htmlapp.use(‘/ user’,userRoutes(app));
在这行代码中,userRoutes(app)应该返回的是函数(req,res [,next]){}
它应该是这样的
app.use('/user',(req,next) => {
userRoutes(app);
next()
})
而你所做的就是
app.use('/user',(app) => {
app.route('/user/signup').post(register);
app.route('/user/login').post(login);
})
那是错的
这里似乎有一些不好的逻辑,因为根据我的理解,你将不得不调用http:// localhost / user来初始化路由,并且由于express的中间件包含而无法正常工作.
根据我的理解,你要做的事情应该更像是这样
...
import userRoutes from './src/routes/userRoutes';
import invoicesRoutes from './src/routes/invoicesRoutes';
...
const app = express();
userRoutes(app);
invoicesRoutes(app);
和
import { register,login } from '../controllers/authController';
import authMiddleware from "./middleware";
const userRoutes = (app) => {
app.post('/user/signup',register);
app.post('/user/login',login);
};
export default userRoutes;