user7366497
user7366497

Reputation:

Router.use() requires middleware function but got a string?

I have looked on the forums and have tried fixing everything I could, but still can't seem to get it to work. I am wanting to use router instead of having to use app.get. I have another project in which I am doing the same thing and it works just fine. So I am a little confused as to why this one isn't working. Thank you very much.

Here is my app.js:

var express = require("express");
var app = express();
var indexRoutes = require("./routes/index.js");

app.use("view engine", "ejs");
app.use(express.static(__dirname + "/public"));

app.use("/", indexRoutes);

app.listen(process.env.PORT, process.env.IP, function() {
    console.log("server started on port : " + process.env.PORT);
});

Here is the route I am using:

var express = require("express");
var router = express.Router();
var multer = require("multer");
var storage = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, './uploads');
    },
    filename: function(req, file, callback) {
        callback(null, file.fieldname + '-' + Date.now());
    }
});
var upload = multer({storage: storage}).single('userPhoto');


router.get("/", function(req, res) {
   res.render("index"); 
});

router.post("/uploads", function(req, res) {
    upload(req, res, function(err) {
        if(err) {
            return res.send("error uploading file");
        }
        res.end("file is uploaded");
    });
});

module.exports = router;

Upvotes: 0

Views: 1408

Answers (3)

Raviteja
Raviteja

Reputation: 1

change this

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

to

app.set("view engine",'ejs');

Upvotes: 0

robertklep
robertklep

Reputation: 203231

This obviously isn't right:

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

It should be:

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

FWIW, if you closely look at the stack trace that accompanied the error, you would have found the exact line in app.js that triggered the error:

TypeError: Router.use() requires middleware function but got a string
    at Function.use (/private/tmp/node_modules/express/lib/router/index.js:458:13)
    at EventEmitter.<anonymous> (/private/tmp/node_modules/express/lib/application.js:220:21)
    at Array.forEach (native)
    at EventEmitter.use (/private/tmp/node_modules/express/lib/application.js:217:7)
    at Object.<anonymous> (/private/tmp/t/app.js:5:5)     <--- there!
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)

Upvotes: 1

Paolo
Paolo

Reputation: 734

i think you have to change this line:

app.use("/", indexRoutes);

with this:

app.use(indexRoutes);

more infos here: TypeError: Router.use() requires middleware function but got a Object

Upvotes: 0

Related Questions