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

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;

Maybe it is because you are not importing express correctly in todo-route.js
it should be:
```
const express = require("express");
```

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

TypeError('app.use() requires a middleware function')

enter image description here
here's the app.js(--please find attached image):
//here's the app.js
const express = require("express");
const app = express();
app.use(express.json());
const morgan = require("morgan");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv/config");
const authJwt = require("./helpers/jwt");
const errorHandler = require("./helpers/error-handler");
app.use(cors());
app.options('*', cors());
//middleware
app.use(morgan("tiny"));
app.use(authJwt());
app.use(errorHandler()); //-> **this isn't correct?**
//Importing routing of products
const categoriesRoutes = require("./routes/categories");
const productsRoutes = require("./routes/products");
const usersRoutes = require("./routes/users");
const ordersRoutes = require("./routes/orders");
const req = require("express/lib/request");
const res = require("express/lib/response");
const api = process.env.API_URL;
//routers
app.use(`${api}/products`, productsRoutes);
app.use(`${api}/categories`, categoriesRoutes);
app.use(`${api}/orders`, ordersRoutes);
app.use(`${api}/users`, usersRoutes);
//Database
mongoose
.connect(process.env.CONNECTION_STRING, {
useNewurlParser: true,
useUnifiedTopology: true,
dbName: "eshop-database",
})
.then(() => {
console.log("database connection is ready");
})
.catch((err) => {
console.log(err);
});
//Server
app.listen(3000, () => {
console.log("Server is Running http://http://localhost:3000");
});
//error image
//here's the error handler code
function errorHandler(err, req, res, next){
if (err) {
res.status(500).json({message: err})
}
}
module.exports = errorHandler;
> Blockquote (--please find attached image)
here's the error
C:\Users\steve\Backend\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function
at Function.use (C:\Users\steve\Backend\node_modules\express\lib\application.js:210:11)
at Object.<anonymous> (C:\Users\steve\Backend\app.js:17:5)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
Your error handler function is correct, but the problem is that you're calling the function instead of passing it directly to your express app.
Remove the parenthesis after the errorHandler and it should work.
app.use(errorHandler); // Don't call errorHandler, express will call it
Think of it like this.
if I just call errorHandler() in any context it won't return anything.
That means that errorHandler() evaluates to undefined.
Now in your code, when you do app.use(errorHandler()) instead of evaluating to the following:
app.use(function(err, req, res, next){
if (err) {
res.status(500).json({message: err})
}
});
Your code is actually evaluating to
app.use(undefined);
and so express is throwing an error because undefined is not a function.

Facing problems while using HBS

I am a total noob in Backend and I am learning Express and using HBS as template engine.
This happens to me every time while using hbs partials in Express.
Code
const express = require("express");
const app = express();
const hbs = require("hbs");
const path = require("path");
const port = process.env.PORT || 3000;
// public static path
const static_path = path.join(__dirname, "../public");
const templates_path = path.join(__dirname, "../templates/views");
const partials_path = path.join(__dirname, "../templates/partials");
app.set("view engine", "hbs");
app.set("views", templates_path);
hbs.registerPartial(partials_path);
app.use(express.static(static_path));
// routing
app.get("/", (req, res) => {
res.render("index");
});
app.get("/about", (req, res) => {
res.render("about");
});
app.get("/weather", (req, res) => {
res.render("weather");
});
app.get("*", (req, res) => {
res.status(404).render("404error");
});
app.listen(port, () => {
console.log("listning on port " + port);
});
Error
throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
^
Error: Attempting to register a partial called "D:\Projects\ExpressWeb\templates\partials" as undefined
at HandlebarsEnvironment.registerPartial (D:\Projects\ExpressWeb\node_modules\handlebars\dist\cjs\handlebars\base.js:80:15)
at Instance.registerPartial (D:\Projects\ExpressWeb\node_modules\hbs\lib\hbs.js:222:35)
at Object.<anonymous> (D:\Projects\ExpressWeb\src\app.js:15:5)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47 {
description: undefined,
fileName: undefined,
lineNumber: undefined,
endLineNumber: undefined,
number: undefined
}
Adding this to increase the discripting because Stack Overflow is not letting me post this because i am uplaoding more code than discription and i dont know what to ask more.
According to the docs it is - hbs.registerPartials(partials_path);
not hbs.registerPartial(partials_path);

how to use Tesseract.recognize in nodejs

I want to make an OCR program but I fund some problems during the declaration of 'Tesseract.recognize' method
here is my code :
const express = require('express');
const fs= require('fs');
const multer = require('multer');
const Tesseract = require('Tesseract.js');
const app = express();
// app.use(bodyParser.urlencoded({extended: true}))
const PORT = process.env.PORT | 5000;
var Storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, 'images')
},
filename: function (req, file, callback) {
callback(null, file.orignalname);
}
});
var upload = multer({
storage: Storage
}).array('image', 3);
//route
app.post('/', (req, res) => {});
app.post('/upload', (req, res) => {
console.log(req.file);
upload(req, res , err => {
if (err) {
console.log(err);
return res.send('somthing went wrong');
}
return res.send('file uploaded successfully');
});
});
var image = fs.readFileSync(__dirname + '/images/cv.jpg',
{
encoding:null
});
Tesseract.recognize(image)
.progress(function(p) {
console.log('progress', p);
})
.then(function(result) {
res.send('result', result);
});
app.listen(PORT, () => {
console.log('Server running on PORT ${PORT}')
});
and this is my terminal result:
.progress(function(p) {
^
TypeError: Tesseract.recognize(...).progress is not a function
at Object.<anonymous> (C:\Users\de\Desktop\MR.Azmani Project\ANGULAR\ocr\server.js:46:6)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
[nodemon] app crashed - waiting for file changes before starting...
and this it what is the result how should look like in the treminal during the process
and this is the final result in the termilal
thank you
.progress was removed in version 2 of tesseract.js (there's a blog post about that here. Version one is still on Github here, and probably still works, so you can npm i tesseract.js#1.0.19 to get the behavior you're expecting, or see the docs and examples for the current version to get your code updated for v2.

Why I get TypeError('Router.use()

I have index.js file like this and
const express = require('express');
const app = express();
//Import Routes
const authRoute = require('./routes/auth');
//Route Middlewares
app.use('/api/user', authRoute);
app.listen(3000, () => console.log('Server Up and running'));
auth.js like this one
const router = require('express').Router();
router.post('/register', (req, res) => {
res.send('Register');
})
module.exports = router;
Why i get the TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a Object
at Function.use (C:\Users\xxx\Desktop\Websites\Authentication\node_modules\express\lib\router\index.js:458:13)
at Function. (C:\Users\xxx\Desktop\Websites\Authentication\node_modules\express\lib\application.js:220:21)
You may try to re-write your auth.js in the following format, I think that will solve the issue:
router.route('/register').post((req, res) => { .............

Keep getting TypeError that comes back as undefined

I am trying to get my Node.js server up and running locally, but it keeps coming back as an ERROR specifically:
/Users/rogerjorns/Desktop/templateassignment/node_modules/express/lib/router/index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a undefined
at Function.use (/Users/rogerjorns/Desktop/templateassignment/node_modules/express/lib/router/index.js:458:13)
at Function.<anonymous> (/Users/rogerjorns/Desktop/templateassignment/node_modules/express/lib/application.js:220:21)
at Array.forEach (<anonymous>)
at Function.use (/Users/rogerjorns/Desktop/templateassignment/node_modules/express/lib/application.js:217:7)
at Object.<anonymous> (/Users/rogerjorns/Desktop/templateassignment/app.js:16:5)
at Module._compile (internal/modules/cjs/loader.js:868:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:879:10)
at Module.load (internal/modules/cjs/loader.js:731:32)
at Function.Module._load (internal/modules/cjs/loader.js:644:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:931:10)`
I am using Node.js, Express and EJS template.
Here is my code for the routes:
app.js
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('view engine', 'ejs');
const indexData = require('./routes/index');
const userRoutes = require('./routes/users');
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/index', indexData.routes);
app.use(userRoutes);
app.use((req, res, next) => {
res.status(404).render('404', { pageTitle: 'Page Not Found', path:'/' });
});
app.listen(5000);
path.js
const path = require('path');
module.exports = path.dirname(process.mainModule.filename);
index.js
const path = require('path');
const express = require('express');
const rootDir = require('../util/path');
const indexData = require('./index');
const router = express.Router();
router.get('/', (req, res, next) => {
const users = indexData.users;
res.render('index', {
users: users,
pageTitle: 'Main',
path: '/',
hasUsers: users.length > 0,
activeIndex: true,
indexCSS: true
});
});
// exports.routes = router;
module.exports = router;
users.js
const path = require('path');
const express = require('express');
const rootDir = require('../util/path');
const router = express.Router();
const users = [];
// GET
router.get('/users', (req, res, next) => {
res.render('users', {
pageTitle: 'Users Page',
path: '/index/add-users',
formsCSS: true,
indexCSS: true,
usersCSS: true,
activeUsers: true
});
});
// POST
router.post('/add-users', (req, res, next) => {
users.push({ title: req.body.title });
res.redirect('/');
});
exports.routes = router;
exports.users = users;
It keeps coming up with that error.
I have been pouring over this for a long time and am still kind of new at this.
Something I have tried is to replace 'module.exports = route;' in index.js with 'exports.router;', and that seems to take away the error but my page then just comes up as 404 error no matter what I type in.
What am I doing wrong? Any insight here would be great.
You switched up indexData and userRoutes:
app.use('/index', indexData.routes);
app.use(userRoutes);
should be
app.use('/index', indexData);
app.use(userRoutes.routes);

Categories

Resources