我正在制作一个登录系统的nodejs api,但是当我添加注册路由时,它给了我类似的错误,我正在使用express@^4.16
C:\projects\mernapp\backend\node_modules\express\lib\router\index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a Object
at Function.use (C:\projects\mernapp\backend\node_modules\express\lib\router\index.js:458:13)
at Function.<anonymous> (C:\projects\mernapp\backend\node_modules\express\lib\application.js:220:21)
at Array.forEach (<anonymous>)
at Function.use (C:\projects\mernapp\backend\node_modules\express\lib\application.js:217:7)
at Object.<anonymous> (C:/projects/mernapp/backend/src/app.js:18:5)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at loader (C:\projects\mernapp\backend\node_modules\babel-register\lib\node.js:144:5)
at Object.require.extensions.(anonymous function) [as .js] (C:\projects\mernapp\backend\node_modules\babel-register\lib\node.js:154:7)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at Object.<anonymous> (C:\projects\mernapp\backend\node_modules\babel-cli\lib\_babel-node.js:154:22)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
[nodemon] app crashed - waiting for file changes before starting...
我确实在Google上搜索了此错误,但我也在stackoverflow上发现了一些问题,但这没有用。 Router.use() requires a middleware function but got a undefined
这是我的代码 app.js
import auth from './routes/auth';
import user from './routes/user';
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/api/auth', auth);
app.use('/api/user', user);
路线/注册
import express from 'express';
import bcrypt from 'bcrypt';
import validateRegisterInput from '../validation/register';
import User from '../models/User';
const router = express.Router();
router.post('/register', function (req, res){
const { errors, isValid } = validateRegisterInput(req.body);
if(!isValid) {
return res.status(400).json(errors);
}
User.findOne({
email: req.body.email
}).then(user => {
if (user) {
return res.status(400).json({
email: 'Email already exists'
});
} else {
const newUser = new User({
firstname: req.body.firstname,
lastName: req.body.lastname,
email: req.body.email,
password: req.body.password
});
bcrypt.genSalt(10, (err, salt) => {
if (err) console.error('There was an error', err);
else {
bcrypt.hash(newUser.password = hash);
newUser
.save().then(user => {
res.json(user)
});
}
})
}
})
})