Facing problems while using HBS - javascript

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);

Related

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

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

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.

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.

Type error: cannot find module body-parser

I tried making a project on my own and this error happened. I couldn't fix it. It just somehow happens and I am so confused where to start looking for the error.
app.js
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('view engine', 'ejs');
app.set('views', 'views');
const adminData = require('./routes/admin');
const shopRoutes = require('./routes/shop');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/admin', adminData.routes);
app.use(shopRoutes);
app.use((req, res, next) => {
res.status(404).render('404', { pageTitle: 'Page Not Found' });
});
app.listen(3000);
admin.js
const path = require('path');
const express = require('express');
const rootDir = require('../util/path');
const router = express.Router();
const products = [];
// /admin/add-product => GET
router.get('/add-product', (req, res, next) => {
res.render('add-product', {
pageTitle: 'Add Product',
path: '/admin/add-product',
formsCSS: true,
productCSS: true,
activeAddProduct: true
});
});
// /admin/add-product => POST
router.post('/add-product', (req, res, next) => {
products.push({ title: req.body.title });
res.redirect('/');
});
exports.routes = router;
exports.products = products;
shop.js
code snippet of shop.js
This is my error.
I am making a webpage for the first time using this.
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module 'body-parser'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\Users\User\Documents\My Website\05-working-on-layout-with-partials\app.js:4:20)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
[nodemon] app crashed - waiting for file changes before starting...
Please try to install the required body-parser module,
Use following command to do so.
npm install body-parser
Please install the dependency i.e body-parser
npm i body-parser --save
Error is on the 4th line of app.js its not getting the body-parser module

Express JS REST API with MySQL

I am doing an exercise with Express.js and MySQL. At the moment I have 4 files. The error is,
TypeError: areas.getAreas is not a function
at Object.<anonymous> (/--/--/--/src/routes/userRoutes.js:4:13)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/--/--/--/src/app.js:10:20)
at Module._compile (module.js:653:30)
But I am sure I am declaring the variable and function so, I don't understand why is it happening.
I tried to get the value of the variable areas in the userRoutes.js file but console just show me an "{}". I also tried to change the sintaxis of the function of the areas.js file, writing it as function and not like an object.
The main file is, app.js and it contains:
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = require('/--/--/--/db/connection.js');
const userRoutes = require('/--/--/--/routes/userRoutes.js');
app.set('port', process.env.PORT || 3000);
app.use(morgan('dev'));
app.use(bodyParser.json());
connection(mysql);
userRoutes(app);
app.listen(app.get('port'), ()=> {
console.log('server on port 3000');
});
The next files are:
connection.js
'use strict';
module.exports = function connection(mysql){
mysql.createConnection({
host: 'http://x.x.x.x',
user: 'xxxxxxx',
password: 'xxxxxxx',
database: 'xxxxxxx'
})
};
areas.js
'use strict';
let areasModel = {};
areasModel.getAreas = (callback) => {
if(connection) {
connection.query(
"SELECT * FROM areas",
(err, rows) => {
if(err) {
throw err;
}
else {
callback(null, rows);
}
}
);
}
};
module.exports = areasModel;
userRoutes.js
'use strict';
const areas = require('../models/areas');
module.exports = function (app) {
app.get("/", (req,res)=>{
areas.getAreas((err, data) => {
res.json([]);
});
});
}
try importing connection.js in areas.js,
maybe because never enter in that if statement, returns undefined

Categories

Resources