Router.use()需要一个中间件函数,但在我的节点文件中有一个Object

时间:2018-01-16 11:20:42

标签: node.js

Node新手,请解决错误 Router.use()需要一个中间件函数但是有一个Object

const bodyParser = require('body-parser');
const express = require('express');
const app = express();

var productRoutes = require('./api/routes/product');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))

app.use('/products', productRoutes);

module.exports = app;

api/routes/product.js

const express = require('express');
const router = express.Router();
router.get('/', (req, res, next) => { 
  res.status(200).json({message: "Here we are handling the get request for the products"});
});

2 个答案:

答案 0 :(得分:4)

您更改了api/routes/product代码。会很好。

const express = require('express');
const router = express.Router();
router.get('/', (req, res, next) => {
    res.status(200).json({
        message: "Here we are handling the get request for the products"
    });
});

module.exports = router;

原因是当您在要导出的文件中写入module.exports = router;时,您没有将路由器导出到其他文件。

答案 1 :(得分:0)

app.use('/products', productRoutes);

productRoutes应该是这个参数的函数(req,res,next)。它可能是这样的:

app.use('/products', function(req, res, next) {
    // Do the things here
});

如果你的productRoutes模块中有这样的函数,你可以导出该函数并将其作为app.use调用中的第二个参数传递