Image in Node JS Images Folder Not Showing on Site - node.js

I am trying to add an image to my index.ejs file, but my code is not pulling the image from the /image folder specified in my second code block. Can anyone help me find the solution to my issue?
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const { path } = require('express/lib/application');
const { HTTPRequest } = require('puppeteer');
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://127.0.0.1:27017';
app.use('/public/images', express.static('/public/images'));
//setup connection
MongoClient.connect(url, {useUnifiedTopology: true})
.then(client => {
console.log('connected to database');
const db = client.db('user-signup-info');
const manateeCollection = db.collection('manatees');
})
//----------middleware------------
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
//----------routes----------------
//going to index.ejs and reading database entries
app.get('/', (req, res) =>{
db.collection('manatees').find().toArray()
.then(manatees => {
res.render('index.ejs', {manatees: manatees})
})
.catch(/*....*/)
})
//grabbing form data and adding to database
app.post('/manatees', (req, res)=>{
//console.log(req.body);
manateeCollection.insertOne(req.body)
.then(result =>{
//console.console.log(result);
res.redirect('/');
})
.catch(error => console.error(error));
})
//----------server----------------
app.listen(3000, function(){
console.log('server is running');
})
//----------end of connection-----
.catch(console.error);
<img src="/images/Manatee_CGrant_VisitCitrus-1200x500.jpg">

Try to change your middleware to -
app.use(express.static('public/images'))

Related

I want to be redirected to a file.js after when i am logged in

This is my Express code by using handlebars using .hbs code
const express = require("express");
const path = require("path");
const app = express();
const port = 3001;
//for mongo all mongodata
require("dotenv").config();
const cors = require("cors");
app.use(cors());
const Handle = require("./views/mongoschema");
const staticPath= path.join(__dirname, "./views");
app.set("view engine","hbs");
app.use(express.static(staticPath));
//for maintaining the format
app.use(express.json());
//to GET the data in the from the form
app.use(express.urlencoded({extended:false}));
//to render the page this is coming (1st)
app.get("/",(req, res) => {
res.render('index');
});
//for login validation
app.post("/mongoschema",async(req, res) => {
try {
const handleData = new Handle({
title: req.body.one,
description: req.body.two,
url: req.body.four
})
const handled = await handleData.save();
//After REGISTRATION sending the user to index file
***res.status(201).render("index");***
} catch (error) {
res.status(400).send(error);
}
});
app.get("/pages", (req, res) => {
Handle.find({})
.then((items) => res.json(items))
.catch((err) => console.log(err));
});
app.listen(port, () => {
console.log('listening to the port ${port)');
});
the file i want to run now is a "file.js" and index is "index.hbs" it is not able to render the "file.js" how can i render or i will be redirected to the "file.js" file After when my login is SUCCESSFUL.
As someone mentioned in the comments, you should be using:
res.redirect("/"); // path to route as parameter - in this case, index.

why my controller function is not getting executed?

I have a simple app with database and i am having issues with controller function. It's not getting executed for some reason that i couldn't figure it out and it drove me crazy. I will be so grateful if you guys could help with me this.
userController.js
exports.insertUser = async (req, res, next) => {
try {
const user = await MySQL.insertRecord(User, { ...req.body })
res.status(201).send(user)
} catch (e) {
res.status(500).send(e)
}
}
insertion function in db.js
static async insertRecord (User, body) {
console.log(1) // for debugging purposes
const user = User.build(body)
try {
await user.save()
console.log('Record saved to database succesfully.')
return user
} catch (e) {
throw e
}
}
userRoutes.js
const express = require('express')
const userController = require('../controllers/userController')
const router = express.Router()
router
.post('/signup', userController.insertUser)
module.exports = router
server.js
(async () => {
const express = require('express')
require('dotenv').config()
const path = require('path')
const { Sequelize } = require('sequelize')
const MySQL = require('./database/db')
await MySQL.connect(Sequelize)
const userRouter = require('./routes/userRoutes')
const app = express()
const PORT = process.env.PORT || 3000
// setting ejs as the templating language
app.set('view engine', 'ejs')
// middlewares
app.use(express.json())
app.use(express.static(path.join(__dirname, 'public')))
app.use('/user', userRouter)
app.listen(PORT, () => console.log(`server listening on port: ${PORT}`))
})()
Here my insertRecord function is not getting executed. It doesn't log 1.

Export the data from a Mongo DB database in a CSV

I have a project in Node JS in which I want to export the data contained in the database in Mongo DB in a CSV file through a button in the view (index.ejs).
I am using mongoose for the connection to the database and to export the data to the CSV I am trying to use json-2-csv.
In the button I have added a url to be able to call that url through the button and that the json-2-csv function responds to that url but I don't know how to do it or if it is the best way.
This is my app.js:
const fs = require('fs');
const json2csv = require("json2csv").Parser;
const userModel = require('./models/users');
const express = require("express");
const app = express();
app.get('/export/csv', async (req, res) => {
await userModel.find((err, data) => {
if (err) throw err;
const json2csvParser = new json2csv({ header: true });
const csvData = json2csvParser.parse(data);
fs.writeFile("users.csv", csvData, function(error) {
if (error) throw error;
console.log("Write to bezkoder_mongodb_fs.csv successfully!");
});
});
});
This is the button:
<form action="/export/csv" mehotd="GET">
<button id="export-csv">Export CSV</button>
</form>
You can achieve all these things in your single file app.js file. We need to have json2csv module because this module has the parser class so that we can use parse() method to get the CSV format data as String. Here lean options tell mongoose to skip instantiating a full Mongoose document and just give you the Plain Old JavaScript Object POJO. And also I have used username and password as documents so change it accordingly.
const path = require('path');
const ejs = require('ejs');
const fs = require('fs');
const express = require('express');
//You need to have some documents into your DB first
const Collection = require('your/Modal Path');
const Json2csvParser = require("json2csv").Parser;
const app = express();
const port = process.env.PORT || 3000;
//Templating Engine Ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
//Middleware
app.use(express.urlencoded({
extended: true
}));
app.use(express.json());
//MONGO DB CONNECTION
const url = 'mongodb://localhost:27017/users';
mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log('Successfully Established Connection with MongoDB')
}).catch(err => {
console.log('Failed to Establish Connection with MongoDB with Error: ' + err);
process.exit();
});
app.get('/export/csv', async (req, res) => {
await Collection.find({}).lean().exec((err, data) => {
if (err) throw err;
const csvFields = ['_id', 'username', 'password']
console.log(csvFields);
const json2csvParser = new Json2csvParser({
csvFields
});
const csvData = json2csvParser.parse(data);
fs.writeFile("bezkoder_mongodb_fs.csv", csvData, function(error) {
if (error) throw error;
console.log("Write to bezkoder_mongodb_fs.csv successfully!");
});
res.send('File downloaded Successfully')
});
});
//HOME route
app.get('/', (req, res) => {
res.render('home.ejs');
});
//listening to the PORT Number
app.listen(port, console.log(`Server is running at ${port}`));
So, this is how your app.js file will look like. And also create a home.ejs file inside views directory like views/home.ejs. and add the below code:
<form action="/export/csv" mehotd="GET">
<button id="export-csv">Export CSV</button>
</form>

Cannot retrieve Users data from database. Server doesnt respond

I am learning a MERN stack course on Udemy and currently I am trying to retrieve the user's data from the server but I can't. I am able to retrieve the post data but the connections times out for users data. Can you guys help me find out what went wrong? Thank you in advance!
userController snippet:
exports.allUsers = (req, res) => {
const users = User.find({})
.then((users) => {
console.log(users);
})
.catch(err => console.log(err));
};
User routes snippet
const express = require('express'),
router = express.Router(),
{userById, allUsers } = require('../controllers/userController');
router.get('/users', allUsers);
router.param('userID', userById)
module.exports = router;
app.js code snippet
const express = require('express'),
app = express(),
postRoutes = require('./routes/post'),
authRoutes = require('./routes/auth'),
morgan = require("morgan"),
mongoose = require("mongoose"),
bodyParser = require("body-parser"),
cookieParser = require('cookie-parser'),
userRoutes = require('./routes/user'),
expressValidator = require('express-validator');
require('dotenv').config();
mongoose.connect(process.env.MONGO_URI,
{ useUnifiedTopology: true, useNewUrlParser: true })
.then(() => console.log("DB connected"));
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(expressValidator());
app.use('/', postRoutes);
app.use('/', authRoutes);
app.use('/', userRoutes);
app.use(function (err, req, res, next) {
if (err.name === 'UnauthorizedError') {
res.status(401).json({error: "Unauthorised"});
}
});
app.listen(process.env.PORT || 3000, () => {
console.log(`SERVER AT PORT: 3000`);
});
Postman gets stuck here:
You have to end the request / respond to the request . In your userController you are missing ending/responding the request. You are just logging the user result .
Try this :
exports.allUsers = (req, res) => {
const users = User.find({})
.then((users) => {
console.log(users);
res.status(200).json(users);
})
.catch((err) => {
console.log(err);
res.status(500).json(err.message);
});
}

Can't use axios to get/post data from/to localhost server in android 7.0 device - React Native app

I use Axios in my react native app. I use Mobiistar Zumbo J2 with Expo to test but I get err: Network Error. I also set CORS for my node server but it still doesn't work. I test with Postman it work normally. Here is my code:
server.js
const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const index = require("./routes/index");
const bookings = require("./routes/bookings");
const cors = require('cors'); // Yep, you need to install this
const app = express();
const port = process.env.PORT || 3000;
app.use(cors());
app.listen(port, () => {
console.log('Server is running on port', port);
});
app.set("views", path.join(__dirname, "views"));
app.set("view engine", 'ejs');
app.engine("html", require("ejs").renderFile);
//Body parser MW
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
//Routes
app.use("/", index);
app.use("/api", bookings);
bookings.js
const express = require("express");
const router = express.Router();
const mongojs = require("mongojs");
const db = mongojs("mongodb://<username>:<password>#ds139614.mlab.com:39614/booking-car-app", ["bookings"]);
router.get("/bookings", (req, res, next) => {
db.bookings.find((err, data) => {
if (err) {
res.send(err);
}
res.json(data);
});
});
router.post("/bookings", (req, res, next) => {
const booking = req.body;
if (!booking.userName) {
res.status(400);
res.json({err: "Bad data"});
} else {
db.bookings.save(booking, (err, savedBooking) => {
if (err) {
res.send(err);
}
res.json(savedBooking);
})
}
})
module.exports = router;
using Axios to get data from server
axios.get("http://127.0.0.1:3000/api/bookings/")
.then(res => {
console.log("Get booking info: ", res);
alert(res);
})
.catch(err => console.log(err))
Error:
Network Error
Stack trace:
node_modules\axios\lib\core\createError.js:16:24 in createError
node_modules\axios\lib\adapters\xhr.js:87:25 in handleError
node_modules\event-target-shim\lib\event-target.js:172:43 in dispatchEvent
node_modules\react-native\Libraries\Network\XMLHttpRequest.js:578:29 in setReadyState
node_modules\react-native\Libraries\Network\XMLHttpRequest.js:392:25 in __didCompleteResponse
node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:191:12 in emit
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:349:47 in __callFunction
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:106:26 in <unknown>
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:297:10 in __guard
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:105:17 in callFunctionReturnFlushedQueue
...
Please help me.
Thank you very much
Android uses a special type of IP address 10.0.2.2
axios.get("http://10.0.2.2:3000//api/bookings/")
.then(res => {
console.log("Get booking info: ", res);
alert(res);
})
.catch(err => console.log(err))

Resources