Home > Software design >  TypeError: Router.use() requires a middleware function but got a string at Function.use
TypeError: Router.use() requires a middleware function but got a string at Function.use

Time:12-28

I'm new to Node and ExpressJs development, however, I cannot import a module router created by me as an exercise.

It gives me this error:

TypeError: Router.use () requires a middleware function but got a string
     at Function.use

I have already tried the module.exports solution, but it doesn't work. The initialize function also fails.

Here are the versions I am working with:
Node version: v10.19.0
Express version: 4.17.2

Index.js

    const express = require('express');
const app = express();
const ProgettoRouting = require("./routing/ProgettoRouting");

app.use("view engine","jade");
app.use(express.static("public"));
//Codifica dati json con questo middlware senza uso
//del pacchetto npm Body Parser
app.use(express.json());

//Con questo milldelware Importiamo il Router Dati
//dove risiedono le funzionalità del progetto
app.use('/route', ProgettoRouting);

//app.use(app.ProgettoRouting);
//ProgettoRouting.initialize(app);

app.listen(3000, () => {console.log("Server in ascolto sulla porta 3000")});

ProgettoRouting.js

const express = require('express');
const router = express.Router();


router.post("/",(res,req) => {
    let firstName = req.body.nome;
    let lastName = req.body.cognome;
    let message = {nome: firstName, cognome: lastName};
    res.render("index",message);
});

module.exports = router;

CodePudding user response:

You need to use

app.set("view engine","jade");

instead of

app.use("view engine","jade");

as you're intending to set the view-engine property to jade, not setting up a middleware.

  • Related