Display image on pug - image

I'm new to NodeJS world.
I tried to display image from mongodb using pug and node express.
Please see my code and guide me.
customer.pug
extend layouts
block content
h1.container #{title} of #{customer.full_name}
div.container
p Full Name: #{customer.full_name}
p Address: #{customer.address}
p Age: #{customer.age}
img.imageScr1(src=customer.profileimage, alt=customer.full_name)
app.js
const express = require('express');
const path = require('path');
const router = express.Router();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const fs = require('fs');
const multer = require('multer');
// set storage engine
const storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, './uploads/',)
},
filename: function (req, file, cb) {
cb(null, file.fieldname + Date.now() + path.extname(file.originalname));
}
});
// init upload
const upload = multer({
storage: storage
});
// Middlewares
// middleware for Assets - to set public for assets
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// route - homepage
app.get('/', function (req, res) {
Customer.find({}, null, function(err, customers) {
if(err){
console.log(err);
} else{
// customers.profileimage = '/' + customers.profileimage;
// console.log('image prefix::: ' + customer.profileimage);
res.render('index', {
title: 'Customer List',
customers: customers
});
}
});
});
app.post('/customer/add', upload.single('profileimage'), function (req, res) {
var customer = new Customer();
customer.full_name = req.body.full_name;
customer.address = req.body.address;
customer.age = req.body.age;
customer.profileimage = req.file.path;
customer.save(function (err) {
if(err){
console.log(err);
} else{
res.redirect('/');
}
});
});
I got following error when render customer.pug view.
error_console
I found that, if I add '\' before image path 'uploads\profileimage1520473825415.jpg', it displays image.
I tried many ways to do that did not work.
Please help me.
Cheers

Related

Why does Postman show "error 404" when I try to save data into my Mongo database?

I have three files in my MVC architecture for my app.
Models folder:
I have exported the Mongoose schema and model like so:
const User = mongoose.model("User", UserSchema);
module.exports = User;
2. Controllers Folder
I have the following code in my controllers file:
const addUser = require('./../models/clientmodel');
exports.addUser = async (req, res) => {
try {
const newUser = await new addUser.create(req.body);
res.status(201).json({
status: "success",
data: {
newUser
}
});
} catch (err) {
res.status(204).json({
status: 'fail',
message: err
})
}
}
3. Routes folder
const router = express.Router();
router
.route('/')
.get (userControl.add_user)
app.post(userControl.newTour);
module.exports = router;
Why do I get the 404 error message in Postman?
How do I inser a loop?
NB: I am new to programming and learning the MERN stack.
The following code works fine in one folder:
const express = require("express");
const userModel = require("./models");
const app = express();
app.post("/add_user", async (request, response) => {
const user = new userModel(request.body);
try {
await user.save();
response.send(user);
} catch (error) {
response.status(500).send(error);
}
});
app.get("/users", async (request, response) => {
const users = await userModel.find({});
try {
response.send(users);
} catch (error) {
response.status(500).send(error);
}
});
module.exports = app;
I would like to refactor the code in the MVC architecture. When I split the code into controller/route configuration, then things do not work.

Tesseract.js throw Error(data) cannot read properties of undefined (reading '_malloc') in tesseract file

I'm trying to use tesseract to convert image to text by upload image to my web app but got the error in the tesseract create worker.js like _malloc is undefined in throw Error(data).
I'm using tesseract version 2.1.5,
and I wrote the code from the video in 2019, I think maybe tesseract is changed from that time.
This is the error
This is code in app.js
const express = require("express");
const app = express();
const fs = require("fs");
const multer = require("multer");
const {createWorker} = require("tesseract.js");
const worker = createWorker({
logger: m => console.log(m)
});
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("fname");
app.set("view engine", "ejs");
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("Error", err);
worker
.recognize('./uploads/op.png')
.then(result => {
res.send(result.txt);
})
.finally(() => worker.terminate());
});
});
});

node heroku error: connect ECONNREFUSED

I have this CRUD app on heroku connected to Mlab. I have 2 different routes (that submits from a form) data to MLab and an image to an S3 bucket. One route works completely fine. The other route, which is very similar to the first, minus some text inputs, throws an error on Heroku whenever you submit. It actually works fine locally though. If I remove all of the logic associated with the image upload it works too. I'm not sure where I'm going wrong here. I can't figure out why it would work on one almost identical route, but not the other.
This is my app.js code that connects mongoose and router
var router = express.Router();
var eventRoutes = require('./routes/event');
var adminRoutes = require('./routes/admin');
var venueRoutes = require('./routes/venue');
app.use('/', router);
app.use(eventRoutes);
app.use(adminRoutes);
app.use(venueRoutes);
mongoose.connect(process.env.HOTNIGHTDATABASEURL);
app.listen(process.env.PORT || 3000, function(){
var date = new Date()
console.log('Server Spinning Up at ' + date.toLocaleTimeString('en-US',
{hour12: true,}));
});
This is the config for S3 and the post route for the route that works.
//Multers3 and AWS s3 setup
var s3 = new aws.S3({
accessKeyId: process.env.HOTNIGHTEVENTSBUCKETID,
secretAccessKey: process.env.HOTNIGHTEVENTSBUCKETSECRET,
region: 'us-east-2'
});
var upload = multer({
storage: multerS3({
s3: s3,
acl: 'public-read',
bucket: 'hot-night-events',
metadata: function (req, file, cb) {
cb(null, {fieldName: file.fieldname});
},
key: function (req, file, cb) {
cb(null, Date.now().toString())
}
})
});
router.post('/events', upload.single('image'), function(req, res){
var event = new Event({
... for brevity left out data collected from form
});
event.save(function(err, data){
if(err){
console.log(err);
} else {
res.redirect('/');
}
});
});
This is the other route (in a different file) that doesn't work:
//Multers3 and AWS s3 setup
var s3 = new aws.S3({
accessKeyId: process.env.HOTNIGHTEVENTSBUCKETID,
secretAccessKey: process.env.HOTNIGHTEVENTSBUCKETSECRET,
region: 'us-east-2'
});
var upload = multer({
storage: multerS3({
s3: s3,
acl: 'public-read',
bucket: 'hot-night-events',
metadata: function (req, file, cb) {
cb(null, {fieldName: file.fieldname});
},
key: function (req, file, cb) {
cb(null, Date.now().toString())
}
})
});
router.post('/venues', upload.single('venueImage'), function(req, res){
var venue = new Venue({
... for brevity left out data collected from form
});
venue.save(function(err, data){
if(err){
console.log(err);
} else {
res.redirect('/');
}
});
});
Any help would be greatly appreciated.

Cannot POST ajax request

can anyone explain to me why i cannot post the ajax request. When i run this code the console appear POST http://localhost:8080/api/users 404 (Not Found), and in the networth part the preview is 404 not found
In the index.js file
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev.js');
var app = express();
var compiler = webpack(config);
var bodyParser = require('body-parser');
var users = require('./server/routes/users');
app.use(bodyParser.json());
app.use('/api/users', users);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(8080, 'localhost', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:8080');
});
and the users file
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
function validateInput(data) {
let errors = {};
if (Validator.isNull(data.username)){
errors.username = "This field is required";
}
if (Validator.isEmail(data.email)) {
errors.email = "Email is invalid";
}
if (Validator.isNull(data.password)){
errors.password = 'This field is required';
}
if (Validator.isNull(data.passwordConfirmation)){
errors.passwordConfirmation = 'This field is required';
}
if (Validator.equals(data.password, data.passwordConfirmation)){
errors.passwordConfirmation = 'Password must match';
}
return {
errors,
isValid: isEmpty(errors)
}
}
router.post('/api/users', (req, res) => {
console.log('runiing the router/post');
console.log(req.body);
const {errors, isValid} = validateInput(req.body);
if (!isValid) {
res.status(400).json(errors);
}
});
module.exports = router
in users.js file the function should be
router.post('/', (req, res) => {
console.log('runiing the router/post');
console.log(req.body);
const {errors, isValid} = validateInput(req.body);
if (!isValid) {
res.status(400).json(errors);
}
});
Because index.js have already resolved /api/users part in the request url http://localhost:8080/api/users at this point. So you only have to map after the /api/users in your users js file.
For example, if you have following function in users.js file
router.post('/:id', (req, res) => {
...
}
It will resole to the path http://localhost:8080/api/users/1
Edit
In your existing version,
router.post('/api/users', (req, res) => {
...
}
will resolve as http://localhost:8080/api/users/api/users

can't get gulp to use browser-sync to refresh an express server and json

I'm learning react and the first thing I wanted was a development environment that could handle the reloading and refreshing for me. I'm following along with their tutorial here:
http://facebook.github.io/react/docs/tutorial.html
Now I wanted to add gulp into this setup. The server ( https://github.com/reactjs/react-tutorial/blob/master/server.js )works fine on its own but doesn't have browser-sync and all the extras that come along with gulp of course.
so what I did was change the server's port to 9000 and proxy the browser-sync in. However, the proxy doesn't seem to pass ajax calls to the server so it can write the json. I've included my gulpfile here.
var gulp = require('gulp');
var sass = require("gulp-ruby-sass");
var filter = require('gulp-filter');
var browserSync = require('browser-sync');
var sourcemaps = require('gulp-sourcemaps');
var server = require('gulp-express');
var reload = browserSync.reload;
gulp.task('server', function(){
server.run(['app.js']);
browserSync({
proxy: "localhost:9000"
});
gulp.watch("./scss/*.scss", ['sass']);
gulp.watch("./app/**/*.html").on('change', reload);
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return sass('./scss', {sourcemap: true})
.pipe(browserSync.reload({stream:true}))
.on('error', function (err) {
console.error('Error!', err.message);
})
.pipe(sourcemaps.write('maps', {
includeContent: false,
sourceRoot: './app/css'
}))
.pipe(gulp.dest('./app/css'));
});
gulp.task('html', function () {
browserSync.reload();
});
// Watch scss AND html files, doing different things with each.
gulp.task('default', ['server'], function () {
gulp.watch("./scss/*.scss", ['sass']);
gulp.watch("./app/**/*.html", ['html']);
});
And here's the app.js file. You can see how it's trying to handle the json.
var fs = require('fs');
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use('/', express.static(path.join(__dirname, 'app')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/comments.json', function(req, res) {
fs.readFile('_comments.json', function(err, data) {
res.setHeader('Content-Type', 'application/json');
res.send(data);
});
});
app.post('/comments.json', function(req, res) {
fs.readFile('_comments.json', function(err, data) {
var comments = JSON.parse(data);
comments.push(req.body);
fs.writeFile('_comments.json', JSON.stringify(comments, null, 4), function(err) {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-cache');
res.send(JSON.stringify(comments));
});
});
});
app.listen(9000);
console.log('Server started: http://localhost:9000/');
Other things I've tried
Before using a proxy. I tried to switch browser-sync's middleware to the express server I had. The problem I ran into is the documentation for this seems to assume I know what I'm doing with express enough to make it work (I mean, the documentation pretty much just shows a console.logged example. Pretty useless).
using middleware
var gulp = require('gulp');
var sass = require("gulp-ruby-sass");
var filter = require('gulp-filter');
var browserSync = require('browser-sync');
var sourcemaps = require('gulp-sourcemaps');
var reload = browserSync.reload;
//server shit
var fs = require('fs');
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// Static Server + watching scss/html files
gulp.task('serve', ['sass'], function() {
browserSync({
server: {
baseDir: "./app",
middleware: function (req, res, next) {
app.use('./', express.static(path.join(__dirname, 'app')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('./comments.json', function(req, res) {
fs.readFile('_comments.json', function(err, data) {
res.setHeader('Content-Type', 'application/json');
res.send(data);
});
});
app.post('./comments.json', function(req, res) {
fs.readFile('_comments.json', function(err, data) {
var comments = JSON.parse(data);
comments.push(req.body);
fs.writeFile('_comments.json', JSON.stringify(comments, null, 4), function(err) {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-cache');
res.send(JSON.stringify(comments));
});
});
});
next();
}
}
});
gulp.watch("./scss/*.scss", ['sass']);
gulp.watch("./app/**/*.html").on('change', reload);
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return sass('./scss', {sourcemap: true})
.pipe(browserSync.reload({stream:true}))
.on('error', function (err) {
console.error('Error!', err.message);
})
.pipe(sourcemaps.write('maps', {
includeContent: false,
sourceRoot: './app/css'
}))
.pipe(gulp.dest('./app/css'));
});
gulp.task('html', function () {
browserSync.reload();
});
// Watch scss AND html files, doing different things with each.
gulp.task('default', ['serve'], function () {
gulp.watch("./scss/*.scss", ['sass']);
gulp.watch("./app/**/*.html", ['html']);
});
The answer is nodemon! nodemon will just restart the server when it sees a change. I don't have to mess with middleware or anything. Then I just proxy browser-sync.
gulp.task('browser-sync', ['sass'], function() {
browserSync({
port: 7000,
proxy: "http://localhost:5000",
files: ["app/**", "scss/**.*.scss"]
});
gulp.watch(sassFolder + '**/*.scss', ['sass']);
gulp.watch(distFolder + '**/*.html').on('change', reload);
});
gulp.task('nodemon', function (cb) {
return nodemon({
script: 'server.js',
ignore: [
'./bower_components/**',
'./node_modules/**',
'./build/**'
]
}).on('start', function () {
cb();
});
});

Resources