Create Troves & Share your joyful moments with pins
express
express --view=ejs
To create in the same opened folder
npm i
npm install -D tailwindcss
npx tailwindcss init
npx nodemon
/views/partials
folderThese include the partials, that are present in all the pages. Example:
index.ejs
paste the below in the body of index.ejs
we’ll write the code in middle
<% include ./partials/header.ejs %> <% include ./partials/footer.ejs %>
index.js
–> get the route & render it from views
folder.router.get('/register', function(req, res, next) {
res.render('register');
});
views
folderregister.ejs
register.ejs
users.js
& creating our database.npm i mongoose passport passport-local passport-local-mongoose express-session multer
users.js
:const mongoose = require('mongoose');
const plm = require("passport-local-mongoose");
mongoose.connect("mongodb://127.0.0.1:27017/project_name") // this is setting it up on localhost.
const userSchema = mongoose.Schema({
// user schema should be created / defined here.
});
userSchema.plugin(plm); // this will enable passport to remember users
module.exports = mongoose.model("user", userSchema);
// model() --> Mongoose compiles a model for you.
// with ("name-of-model", Schema-to-be-followed) as 2 arguments are passed.
Multer
& uuid
to take user images and save in our servernpm i multer uuid
Create multer.js
in routes
Add the following code:
const multer = require('multer');
const {v4: uuidv4} = require("uuid");
const path = require('path');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/images/uploads')
},
filename: function (req, file, cb) {
const unique = uuidv4();
cb(null, unique + path.extname(file.originalname));
}
})
const upload = multer({ storage: storage })
module.exports = upload;
./public/images/uploads
is the folder location in public/images/uploads
We are Creating unique image id with uuid
index.js
```js
const upload = require(‘./multer’);/* Route for taking user-input profile image using multer. It will first check, if the user is loggedIn or not Then, upload the image. / router.post(‘/fileupload’, isLoggedIn, upload.single(‘image’), function(req, res, next) { // upload.single(‘image’) has ‘image’ because form has input name = “image” const user = await userModel.findOne({username: req.session.passport.user}); / When user is loggedin –> req.session.passport.user has his “username”.
We are sending the uploaded profile image to the database.*/
user.profileImage = req.file.filename; // changing the profileImage address/location to the newly updated image.
await user.save(); // Since, we have manually did some changes --> We need to manually save the user Details.
res.redirect("/profile"); // After saving the new details, redirect to /profile page. }); ```
profile.ejs
file<img class="object-cover w-full h-full" src="/images/uploads/<%= user.profileImage %>" alt="">
There must not be any spaces in the src, otherwise, it will not get the correct path.
This behavior is expected and indicates that the CSS file is being served correctly by Express. However, if you’ve made changes to the CSS file and you want to force the browser to fetch the latest version, you can do the following:
Force Refresh: You can force a refresh in your browser, which typically bypasses the cache and fetches the latest version of the CSS file. In most browsers, you can do this by pressing Ctrl + Shift + R or Cmd + Shift + R.
# Improvement 1 - Another option to upload images via image url
1. To fetch, install
```shell
npm i axios
npm i https
index.js
const axios = require('axios'); // Import axios for making HTTP requests
const https = require('https'); // Import https module
router.post('/createpost', isLoggedIn, upload.single('postimage'), async function(req, res, next) {
const user = await userModel.findOne({username: req.session.passport.user});
let image;
// Check if the request contains a file uploaded
if (req.file) {
// If a file is uploaded, use the uploaded file
image = req.file.filename;
} else if (req.body.imageUrl) {
// If image URL is provided, fetch the image and save it
try {
const agent = new https.Agent({
rejectUnauthorized: false
}); // Don't add this line for production version. I lost my ssl certificate, that's why I need to bypass this.
const response = await axios.get(req.body.imageUrl, { responseType: 'arraybuffer', httpsAgent: agent });
const imageBuffer = Buffer.from(response.data, 'binary');
const imageName = 'image_' + Date.now() + '.jpg'; // Generate a unique name for the image
const imagePath = './public/images/uploads/' + imageName; // Set the path where the image will be saved
fs.writeFileSync(imagePath, imageBuffer); // Write the image buffer to a file
image = imageName; // Set the image name as the image for the post
} catch (error) {
console.error('Error fetching image from URL:', error);
// Handle error (e.g., image fetch failed)
res.status(500).send('Error fetching image from URL');
return;
}
}
const post = await postModel.create({
user: user._id,
title: req.body.title,
description: req.body.description,
image: image
}); // to create the post data in postModel
user.posts.push(post._id);
await user.save();
res.redirect("/profile");
});
add.js
Default user profile image –> it should be shown for new accounts with no image, or when user wants to delete profile image.
Create Pin
button ki jagah Create Trove
button aayega –> new TroveBoard create krne ke liye.Create Pin
ka. –> + icon
Sabhi boards ko default cover image dena hai (New Pin add krne ke icon ke saath.)
Feed Page should have a Search Bar
to search different pins by all the users
Edit Profile
button