worker.recognize(...).progress is not a function. How to fix? - javascript

my code is:
//Imports
const express = require('express');
const app = express();
const fs = require("fs");
const multer = require('multer');
const { createWorker } = require("tesseract.js");
const worker = createWorker();
//Storage
const storage = multer.diskStorage({
destination: (req,file,cb) => {
cb(null, "./uploads");
},
filename: (req,file,cb) => {
cb(null, file.originalname);
}
});
const upload = multer({storage: storage}).single("avatar");
app.set('view engine', 'ejs');
//route
app.get('/',(req,res)=>{
res.render('index');
});
app.post('/upload',(req,res) => {
upload(req,res, err => {
fs.readFile(`./uploads/${req.file.originalname}`,(err,data) => {
if(err) return console.log('This is your error',err);
worker
.recognize(data, "eng", {tessjs_create_pdf: '1'})
.progress(progress => {
console.log(progress);
})
.then(result => {
res.send(result.text);
})
.finally(() => worker.terminate())
});
});
});
//Start Up our server
const PORT = 5000 || process.env.PORT;
app.listen(PORT, () => console.log(`Hey I am running on port ${PORT}`));
the error I get is this
D:\ML\OCR\app.js:34
.progress(progress => {
^
TypeError: worker.recognize(...).progress is not a function
at D:\ML\OCR\app.js:34:18
I know worker.recognize/.progress is decapitated but can someone please correct this code.
Thank you.
I am trying to create an OCR using tesseract.js . watching this video: https://www.youtube.com/watch?v=a1I3tcALTlc
But I am not able to find a solution.

Change this line
const worker = createWorker();
To
const worker = await createWorker();

I think the issue is that the code is out of date.
Try this
async function getTextFromImage() {
await worker.load()
await worker.loadLanguage('eng')
await worker.initialize('eng')
const { data: { text } } = await worker.recognize(data);
res.send(text);
console.log(text);
await worker.terminate()
}
getTextFromImage();

Related

Why do I get `Cannot read properties of undefined (reading 'collection')` when running 'db.collections' in js code

I'm a very beginner with MongoDB and JS
i'm running nodemon app in the terminal
running MONGODB COMPASS in the background
I'm getting the error:
TypeError: Cannot read properties of undefined (reading 'collection')
at D:\Coding\MongoDB\MongoDB Tutorial\app.js:23:24`
afaik I'm supposed to write db.collections and not db.books directly like I do it in Mongo Shell
db.js
const { MongoClient } = require('mongodb')
let dbConnection;
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
let dbName = 'bookstore'
module.exports = {
// establish connection to the db
connectToDb: async (cb) => {
await client.connect()
.then(client => {
dbConnection = client.db(dbName)
return cb()
})
.catch(err => {
console.log(err);
return cb()
})
},
// return connection to the db
getDb: () => dbConnection
}
app.js
const express = require('express');
const { connectToDb, getDb } = require('./db')
// init app & middleware
const app = express();
// db connection
let db
let PORT = 3000;
connectToDb((err)=>{
if (!err) {
app.listen(PORT, () => {
console.log(`app listening on port ${PORT}`);
});
db = getDb();
}
})
// routes
app.get('/books', async (req, res) => {
// db.books in mongosh
const abc = await db.collection('books').find({});
console.log(abc);
res.json({ msg: 'Welcome to the api' })
})

Transferring data from react js to mongodb

I'm trying to send data from the front-end(react js) to the back-end(node js) and then to mongodb database (so it would be saved there). I called the server successfully with the data, but I'm not able to send the date to the database from the server. These are my files.
react js file: ( this function is called when the user enters some text and clicks on a button )
handleSubmit = () => {
console.log("its running");
let databody = {
message: this.state.val,
};
console.log(" the message is :" + this.state.val);
return fetch("http://localhost:5000/stored", {
method: "POST",
body: databody,
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.then((data) => console.log(data));
};
index.js - nodejs file: (Here is where I'm getting my error which says "TypeError: connectDB.collection is not a function")
const express = require("express");
const cors = require("cors"); // Importing cors
var request = require("request");
const dotenv = require("dotenv");
const port = 5000;
var util = require("util");
const connectDB = require("./config/db");
require("dotenv").config({ path: "./config/config.env" });
const app = express();
dotenv.config();
const db = connectDB();
app.get("/", (req, res) => {
res.send("Hey there!");
});
app.get("/Pinged", function (req, res) {
res.send("Pinged!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
});
app.use(cors({ origin: "*" }));
app.post("/stored", (req, res) => {
console.log("its running 2: " + req.body);
db.collection().insertOne(req.body, (err, data) => {
if (err) return console.log(err);
res.send("saved to db: " + data);
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
db.js file inside config folder:
const mongoose = require("mongoose");
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
});
console.log(`MongoDB Connected : ${conn.connection.host}`);
return conn;
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
module.exports = connectDB;
Here, in db.js you should return conn.connection
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
console.log(`MongoDB Connected : ${conn.connection.host}`)
return conn.connection
} catch (err) {
console.error(err.message)
process.exit(1)
}
}

TypeError: Prismic.getApi is not a function

i'm really struggling while trying to build a website from scratch without a framework. And now i'm integrating Prismic in through node.js, but as I'm following all the passages i'm getting stuck by this error shown in the log of the terminal: TypeError: Prismic.getApi is not a function.
As a consequence of this i can see the local website but the about link doesn't load. How can i fix that?
This is the main code related to the package.json
require('dotenv').config()
console.log(process.env.PRISMIC_ENDPOINT, process.env.PRISMIC_CLIENT_ID)
const express = require('express')
const app = express()
const path = require('path')
const port = 3000
const Prismic = require('#prismicio/client')
const PrismicDOM = require('prismic-dom')
const initApi = req => {
return Prismic.getApi(process.env.PRISMIC_ENDPOINT, {
accessToken: process.env.PRISMIC_ACCESS_TOKEN,
req
})
}
const handlelinkResolver = doc => {
// Define the url depending on the document type
// if (doc.type === 'page'){
// return '/page/' + doc.uid;
// } else if (doc.type === 'blog_post'){
// return '/blog/' + doc.uid;
// }
// Default to homepage
return '/'
}
app.use((req, res, next) => {
res.locals.ctx = {
endpoint: process.env.PRISMIC_ENDPOINT,
linkResolver: handlelinkResolver
}
res.locals.PrismicDOM = PrismicDOM
next()
})
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.get('/', async (req, res) => {
res.render('pages/home')
})
app.get('/about', async (req, res) => {
initApi(req).then((api) => {
api.query(
Prismic.Predicates.at('document.type', 'about')
).then(response => {
console.log(response)
res.render('pages/about')
})
})
})
app.get('/personaggi', (req, res) => {
res.render('pages/personaggi')
})
app.get('/detail/:uid', (req, res) => {
res.render('pages/detail')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
You can use :
const Prismic = require('prismic-javascript')
// NB : This package has been deprecated but it's still working.
Instead of :
const Prismic = require('#prismicio/client')
OR you can use the actual setup guide of Prismic at https://prismic.io/docs/technologies/express-install
As user bmz1 mentionned, getApi() is no longer used in version 6+. Downgrade #prismicio/client.
In your package.json dependencies, replace by :
"#prismicio/client": "5.1.0"
Don't forget to run npm i to reset your dependencies

Node JS CORS module not setting Access-Control-Allow-orgin express header

I am trying to create api and fetch it from front but the "Access-Control-Allow-Origin" is not allowing me.
I tried to solve the problem
but still showing me the problem.
this is the front part
I fetched it by GET method but not working
const api = "http://localhost:3000/api/posts/";
const base_api = "http://localhost:3000/";
console.log(api);
window.onload = () => {
getPost();
};
const getPost = () => {
fetch( api , {
method: "GET",
})
.then((response) => {
return response.json();
})
.then((data) => {
buildPost(data);
console.log(data);
});
};
const buildPost = (blogPost) => {
console.log(blogPost);
*this is the express part
I used the "*" that still showing the error. what more solution could be
const express = require("express");
const app = express();
const Post= require("./api/models/posts");
const postsData= new Post();
app.use((req, res, next) =>{
res.setHeader("Access-Control-Allow-Orgin","*" )
next();
})
app.use(express.json());
app.use ('/uploads', express.static('uploads'))
app.get("/api/posts", (req, res)=>{
res.status(200).send(postsData.get())
});
app.get("/api/posts/:post_id", (req, res)=>{
const postId = req.params.post_id;
const foundedPost= postsData.getEachData(postId);
});
app.listen(3000, ()=> console.log("Listening on
http://localhost:3000/"))

Why does my http request not return a response

I have several routes in my api that work perfectly but while trying to implement a comment system I dont receive any response either from going to the url (node backend) or from postman.
My server JS is as follows and works for post, teams, users, but it does not work for comments.
Server.js File Below:
//load server
const express = require('express');
var cors = require('cors');
const app = express();
const morgan = require('morgan');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const multer = require('multer');
//db
const db = require('./config/db');
db
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
//image upload
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public')
},
filename: function (req, file, cb) {
let date = new Date(Date.now());
cb(null, date.getDay() + '-' + date.getDate() + '-' + file.originalname )
}
})
var upload = multer({ storage: storage }).single('file')
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))
app.use(cors());
app.use(express.static('./public'))
app.use(morgan('combined'));
const router = require('./routes/user.js')
const postRoute = require('./routes/post.js');
app.use('/posts', require('./routes/post.js'));
app.use('/teams', require('./routes/teams.js'));
app.use('/comments', require('./routes/comments.js'));
app.use(router)
app.listen(port, () => console.log(`Listening on port ${port}`));
Below are my comment api routes:
const express =require('express');
const mysql = require('mysql');
const db = require('../config/db');
const Comments = require('../models/Comments');
// const connection = getConnection()
const router = express.Router();
const Sequelize = require('sequelize');
router.get('/', (req, res) =>
Comments.findAll().then( comments => {
console.log(comments);
res.json(comments);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
router.get('/:id', (req, res) =>
Comments.findAll({
where: {
postId: req.params.id
}
}).then( comments => {
console.log(comments);
res.json(comments);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
router.post('/add/:id', (req, res) => {
Comments.create(req.body).then(comments => {
console.log(req.body)
res.json(comments);
console.log(comments)
})
.catch(err => console.log(err))
});
module.exports = router;
Im posting my Teams Api Route To Show what i have that has been working perfectly for me:
//will contain all user routes
const express =require('express');
const mysql = require('mysql');
const db = require('../config/db');
const Teams = require('../models/Teams');
// const connection = getConnection()
const router = express.Router()
const Sequelize = require('sequelize');
//find all teams
router.get('/', (req, res) =>
Teams.findAll().then( team => {
console.log(team);
res.json(team);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
//find Team by ID
router.get('/:id', (req, res) =>
Teams.findAll({
where: {
id: req.params.id
}
}).then( team => {
console.log(team);
res.json(team);
// res.sendStatus(200);
})
.catch(err => console.log(err)));
//add users image
module.exports = router;
It was because It was expecting a request, and i wasnt giving it one. Have to just return response.
router.get('/').then(res => {
Comments.findAll().then(comments => {
console.log(comments);
res.json(comments.data);
})
})

Categories