I have followed the documentation but I sent the post image via postman error - express

I have followed all documentation, token and id are correct, I have checked to send text. it works.
I want to send an image via expressjs and multer, but it doesn't work.
https://www.npmjs.com/package/discord-cloud-database
const multerMiddleware = (req, res, next) => {
const multerStorage = multer.memoryStorage();
return multer({
storage: multerStorage,
}).single("photo");
};
const uploadImageMiddleware = async (req, res, next) => {
try {
const file = req.file;
const image = await discordDatabase.uploadFile(file.buffer, file.originalname, { name: "users" });
req.image = image;
next();
} catch (error) {
next(error);
}
};
const catchAsync = (fn) => {
return (req, res, next) => {
fn(req, res, next).catch(next);
};
};
router.route("/").post(
multerMiddleware,
uploadImageMiddleware,
catchAsync(async (req, res, next) => {
try {
res.status(200).json({
status: "success",
data: {
image: req.image.url,
},
});
} catch (error) {
next(error);
}
})
);
app.listen(3000, () => console.log("server run"));
respon from postman:
respon postman
I want to successfully send an image to discord via postman.

Related

How do I save the state of a page in Express JS?

I'm creating a website that allows users to create a video-board and display YouTube videos, and they can drag/resize these videos. I want users to be able to save their video board page in a unique URL so they can return later, and have multiple different pages.
To do this I've created a unique user id with UUID, and added this to the URL when users create a video board. Then, I connected my website to a MySQL database and used sequelize to create a table using a MVC Pattern. I want to store the state of their video board (positions, videos URL) and assign it to their url. The tables have been created, however, the issue I'm having is nothing is being sent to the database.
GitHub: https://github.com/RyanOliverV/MultiViewer
Controller index:
const controllers = {};
controllers.video = require('./video-board');
module.exports = controllers;
Controller video board:
const { models: { Video } } = require('../models');
module.exports = {
create: (req, res) => {
const { video_url, user_id, position } = req.body;
Video.create({ video_url, user_id, position })
.then(video => res.status(201).json(video))
.catch(error => res.status(400).json({ error }));
},
getAllVideos: (req, res) => {
Video.findAll()
.then(videos => res.status(200).json(videos))
.catch(error => res.status(400).json({ error }));
},
getVideoById: (req, res) => {
const { id } = req.params;
Video.findByPk(id)
.then(video => {
if (!video) {
return res.status(404).json({ error: 'Video not found' });
}
return res.status(200).json(video);
})
.catch(error => res.status(400).json({ error }));
},
update: (req, res) => {
const { id } = req.params;
const { video_url, user_id, position } = req.body;
Video.update({ video_url, user_id, position }, { where: { id } })
.then(() => res.status(200).json({ message: 'Video updated' }))
.catch(error => res.status(400).json({ error }));
},
delete: (req, res) => {
const { id } = req.params;
Video.destroy({ where: { id } })
.then(() => res.status(200).json({ message: 'Video deleted' }))
.catch(error => res.status(400).json({ error }));
},
}
Model index:
const dbConfig = require('../config/db-config');
const Sequelize = require('sequelize');
const sequelize = new Sequelize(dbConfig.DATABASE, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.DIALECT
});
const db = {};
db.sequelize = sequelize;
db.models = {};
db.models.Video = require('./video-board') (sequelize, Sequelize.DataTypes);
module.exports = db;
Model video board:
module.exports = (sequelize, DataTypes) => {
const Video = sequelize.define('video', {
video_url: {
type: DataTypes.STRING,
allowNull: false
},
user_id: {
type: DataTypes.STRING,
allowNull: false
},
position: {
type: DataTypes.JSON,
allowNull: false
}
});
return Video;
}
Route:
const express = require('express');
const router = express.Router();
const { v4: uuidv4 } = require('uuid');
const { video } = require('../../controllers');
router.get('/', (req, res) => {
const user_id = uuidv4();
res.redirect(`/video-board/${user_id}`);
});
router.post('/', (req, res) => {
const { video_url, user_id, position } = req.body;
video.create(req, res, { video_url, user_id, position })
});
router.get('/:id', (req, res) => {
const user_id = req.params.id;
res.render('video-board', { user_id });
});
module.exports = router;
When the user clicks the 'create-video-board' button it creates a unique url, and I'm expecting this to be stored in the database with the page state of that url.

Why do I keep getting this error when trying to set up passport-local-mongoose, after registering a user?

Every time i try to register a new username and password i get this error. Error Message Im not sure if I am doing something wrong. I am trying to learn the different levels of authentication
my code is below
require('dotenv').config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require('express-session');
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const app = express();
app.use(express.static("public"));
app.set('view engine', 'ejs',);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(session({
secret: 'suckbigd please',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect("mongodb://localhost:27017/userDB", { useNewUrlParser: true });
// mongoose.set("useCreateIndex", true);
const userSchema = new mongoose.Schema({
email: String,
password: String
});
userSchema.plugin(passportLocalMongoose);
const User = new mongoose.model("User", userSchema);
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.get("/", function (req, res) {
res.render("home");
});
app.get("/login", function (req, res) {
res.render("login");
});
app.get("/register", function (req, res) {
res.render("register");
});
app.get("/secrets", function (req, res) {
if (req.isAuthenticated()) {
res.render("secrets");
} else {
res.render("/login");
}
});
app.post("/register", function (req, res) {
User.register({ username: req.body.username }, req.body.password, function (err, user) {
if (err) {
console.log(err);
res.redirect("/register");
} else {
passport.authenticate("local")(req, res, function () {
res.redirect("/secrets");
});
}
});
});
app.post("/login", function (req, res) {
const usetr = new User({
username: req.body.username,
password: req.body.password
});
req.login(user, function (err) {
if (err) {
console.log(err);
} else {
passport.authenticate("local")(req, res, function () {
res.redirect("/secrets");
});
}
})
});
app.listen(3000, function () {
console.log("Server started on port 3000.");
});
I thought I followed the course instructions right. I even watched the video and followed along but I am still getting this error. I am banging my head on the key board. I have been trying to fix this for 4 days now and still nothing. Someone please help.

No 'Access-Control-Allow-Origin' header is present on the requested resource (MERN)

This error is never ending, I keep getting it and it's been days I've been trying to find a solution for this annoying error.
Here is what happens when I try to log in.
My app works perfectly fine in localhost but there are alot of issue when I uploaded it to heroku and it is really annoying.
Im using
Axios.defaults.withCredentials = true;
code on my every front end.
My backend
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose")
const app = express();
const bcrypt = require("bcryptjs")
const saltRounds = 10;
const bodyParser = require("body-parser")
const cookieParser = require("cookie-parser")
const session = require("express-session")
const voterModel = require('./modules/voters.js')
const presidentModel = require('./modules/president.js')
const viceModel = require('./modules/vice.js')
const treasurerModel = require('./modules/treasurer.js')
var MongoDBStore = require('connect-mongodb-session')(session);
app.use(express.json());
const corsOptions = {
origin: 'https://incomparable-speculoos-abdd5f.netlify.app',
//update: or "origin: true," if you don't wanna add a specific one
credentials: true,
};
app.use(cors(corsOptions));
app.options('*', cors());
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }))
mongoose.connect("hidden",
{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
var store = new MongoDBStore({
uri: 'hidden',
collection: 'sessions'
});
// Catch errors
store.on('error', function(error) {
console.log(error);
});
app.use(session({
secret: "hidden",
resave: false,
store: store,
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24
}
}))
app.post('/login', async (req, res) => {
const email = req.body.email;
const password = req.body.password;
voterModel.find({email: email}, {"email":1}, async (err, result) => {
if (err) {
console.log(err)
} else {
if(result.length > 0) {
const user = await voterModel.findOne({email: email})
const pass = await user.comparePassword(password)
if (pass) {
req.session.user = user
} else {
console.log("NOT LOGGED IN")
res.send({ message: 'Invalid email or password!'})
}
} else {
console.log("NOT LOGGED IN")
res.send({ message: 'Invalid email or password!'})
}
}
})
})
app.post('/register', async (req, res) => {
const username = req.body.username;
const email = req.body.email;
const password = req.body.password;
// HASING PASSWORD
bcrypt.hash(password, saltRounds, async (err, hash) => {
if (err) {
console.log(err)
}
// INSERTING VALUES
const voters = await voterModel({email: email, username: username, password: hash, status: false})
// CHECKS IF EMAIL IS IN USE
const isNewEmail = await voterModel.isThisEmailInUse(email)
if (!isNewEmail) return res.send({ message: 'This email is already taken!'})
// SAVES THE INSERT DATA FOR VOTERS
await voters.save()
res.send({success: true})
})
})
app.post('/voted', async (req, res) => {
// FOR UPDATING THE VOTING STATUS
const email = req.body.email
// VARIABLES FOR CHOSEN CANDIDATES OF USER
const president = req.body.president
const vice = req.body.vice
const treasurer = req.body.treasurer
// SETS THE STATUS OF VOTER TO TRUE SO HE/SHE CAN ONLY VOTE ONCE
voterModel.updateOne({email: email}, {$set : {status: true}}, (err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
// BELOW ARE THE COMMANDS FOR INCREMENTING THE VOTE COUNT OF SELECTED CANDIDATES OF THE VOTER
presidentModel.updateOne({nickname: president}, {$inc : {votes: 1}}, (err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
viceModel.updateOne({nickname: vice}, {$inc : {votes: 1}}, (err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
treasurerModel.updateOne({nickname: treasurer}, {$inc : {votes: 1}}, (err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
})
app.get('/login', (req, res) => {
if (req.session.user) {
res.send({loggedIn: true, user: req.session.user})
} else {
res.send({loggedIn: false})
}
})
app.post('/checkVote', (req, res) => {
const email = req.body.email
const num = true;
voterModel.find({ $and : [{email: email}, {status : num}]},(err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
if (result.length > 0) {
res.send( {voted: true } )
} else {
res.send( {voted: false } )
}
}
})
})
app.get("/logout", (req, res) => {
req.session.destroy(err => {
if (err) return next(err)
res.status(200).send('logged out')
})
res.status(200).send('User has been logged out');
});
const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
console.log('running on port 3001')
})

How to communicate between microservices using event bus?

I'm trying to send data from one microservice to another through event bus. But still as a result I'm getting an empty data, I don't get what I'm doing wrong, please help.
Trying to send data:
app.get ('/products', async (req , res) => {
let db = await connect();
let cursor = await db.collection('posts').find({});
let doc = await cursor.toArray();
res.json(doc);
if (doc.insertedCount == 1) {
res.send({
status: 'success',
id: results.insertedId,
});
}
else {
res.send({
status: 'fail',
});
}
axios.get('http://localhost:4205/events', {
type: 'Success',
data: {
_id: mongo.ObjectID(id),
doc,
postId: req.params.id,
}
})
});
Event bus:
app.get('/events', async (req, res) => {
const event = req.body;
res.json(event);
axios.get('http://localhost:4202/events', event)
res.send({status:'OK'})
})
Microservice where I want to fetch the data:
app.get('/events', async (req, res) => {
res.send(req.body)
});
First:
app.get('/products', async (req, res) => {
try {
const db = await connect();
const cursor = await db.collection('posts').find({});
const doc = await cursor.toArray();
/* Below are weird code
res.json(doc);
if (doc.insertedCount == 1) {
res.send({
status: 'success',
id: results.insertedId,
});
} else {
res.send({
status: 'fail',
});
}
*/
axios.post('http://localhost:4205/events', {
type: 'Success',
data: {
id: mongo.ObjectID(id),
doc,
postId: req.params.id,
},
});
return res.status(200).send();
} catch (error) {
// Here catch and do something with errors;
console.log(error);
}
});
Second:
app.post('/events', async (req, res) => {
try {
const event = req.body;
console.log(event);
// What's mean next line ?
// res.json(event);
const response = await axios.post('http://localhost:4202/events', event);
console.log(response);
return res.status(200).json({ status: 'OK' });
} catch (error) {
console.log(error);
}
});
Last
app.post('/events', async (req, res) => {
try {
console.log(req.body);
return res.status(200).json(req.body);
} catch (error) {
console.log(error);
}
});

How can I redirect when I login with Passport and google oauth2 integration

I have the following code, the login works but after selecting a Google account it remains loading and does not lead to the url of callbackURL that I have indicated.
/pages/api/auth/google/index.js
import nextConnect from "next-connect";
import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";
const authenticate = (method, options, req, res) =>
new Promise((resolve, reject) => {
passport.authenticate(method, options, (error, token) => {
if (error) {
reject(error);
} else {
resolve(token);
}
})(req, res);
});
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: "http://localhost:3000/api/auth/google/redirect",
passReqToCallback: true,
},
(req, accessToken, refreshToken, profile, done) => {
console.log(profile);
}
)
);
export default nextConnect()
.use(passport.initialize())
.get(async (req, res) => {
try {
await authenticate("google", { scope: ["profile", "email"] }, req, res);
} catch (error) {
console.log(error);
res.end(JSON.stringify({ error: error.message }));
}
});
/pages/api/auth/google/redirect.js
import nextConnect from "next-connect";
import passport from "passport";
export default nextConnect().get(
passport.authenticate("google"),
(req, res) => {
res.writeHead(302, {
Location: "/",
});
res.end();
}
);
Try changing your route with the following: If there's a failure in logging in, the user will be redirected to the /login page, otherwise, it will be redirected to the home page /
export default nextConnect().get(
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
}
);