'how can I use two routes files using express?
//index.js, I want to use all the routes in here.
const express = require("express");
const app = express();
const dotenv = require("dotenv");
const cors = require("cors");
dotenv.config();
app.use(cors());
//importing database conn
const conn = require("./db/conn");
conn();
//import routes
const authRoute = require("./routes/auth");
const productRoute = require("./routes/product");
//middleware
app.use(express.json());
//route middleware
app.use("/api/user", authRoute);
app.use("/user/products", productRoute);
const port = process.env.PORT;
app.listen(port, () => console.log(`gg server is runnig ${port}`));
When i add only authRoute it is working perfectly fine and but when i try to add another route from another file it throws errror saying router.use requires middleware function but got a + gettype(fn)
//products.js
const router = require("express").Router();
const { productValidation } = require("express").Router();
router.post("./product", (req, res) => {
const { error } = productValidation(req.body);
})
Solution 1:[1]
You need to return the router from product.js:
const router = require("express").Router();
const { productValidation } = require("express").Router();
router.post("./product", (req, res) => {
const { error } = productValidation(req.body);
})
module.exports = router
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sina.ce |
