Home > front end >  Router.use() requires a middleware function but got a string
Router.use() requires a middleware function but got a string

Time:09-04

I get this error

E:\server\node_modules\express\lib\router\index.js:469 throw new TypeError('Router.use() requires a middleware function but got a ' gettype(fn)) ^ TypeError: Router.use() requires a middleware function but got a string at Function.use (E:\PROJECT\New folder\New folder\server\node_modules\express\lib\router\index.js:469:13) at Function. (E:\PROJECT\New folder\New folder\server\node_modules\express\lib\application.js:227:21)
at Array.forEach () at Function.use (E:\PROJECT\New folder\New folder\server\node_modules\express\lib\application.js:224:7) at Object. (E:\PROJECT\New folder\New folder\server\index.js:27:5) at Module._compile (node:internal/modules/cjs/loader:1126:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10) at Module.load (node:internal/modules/cjs/loader:1004:32) at Function.Module._load (node:internal/modules/cjs/loader:839:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)

Index.js

const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const todoRoute = "./Routes/todo-route.js";

const app = express();

dotenv.config();
app.use(cors());
app.use(express.json());

mongoose
    .connect(process.env.MONGODB_URI, {
        useNewUrlParser: true,
    })
    .then(console.log("DB Connected successfuly"))
    .catch((error) => {
        console.log(error);
    });

app.get("/", (req, res) => {
    res.send("this is the homepage");
});
app.use("/api/todos", todoRoute);

const PORT = 5000 || process.env.PORT;

app.listen(PORT, () => {
    console.log(`Listening on http://localhost:${PORT}`);
});

todo-route.js

const express = require(express);

const router = express.Router();

router.get("/", (req, res) => {
    res.send("this is get route");
});

router.post("/", (req, res) => {
    res.send("this is post route");
});

router.put("/:id", (req, res) => {
    res.send("this is update route");
});

router.delete("/:id", (req, res) => {
    res.send("this is delete route");
});

module.exports = router;

CodePudding user response:

Maybe it is because you are not importing express correctly in todo-route.js

it should be:

```
const express = require("express");

```

CodePudding user response:

According to official API Reference

second argument of app.use should be a callback function

so in your index.js have a line

app.use("/api/todos", todoRoute);

todoRoute should use require make that become a function

  • Related