why req.body.title shows 'undefined' - javascript

I'm new to NODE JS and practicing with some POST forms from PUG to a NODE JS server.
I have a simple form to update a photo title and description posted onto mongodb. When I submit the form from the web browser the submission input comes back to the server as 'undefined'.
These two processes in POST log 'undefined': (see below with more full code)
console.log("title:", req.body.title)
console.log("description", req.body.description)
I've tried to use PUT instead. Weirdly I've done this before and it's worked. So I'm not sure what the issue is...
router handling the POST request:
//users.js
const express = require('express');
const router = express.Router();
const app = express();
const multer = require('multer');
const photoController = require('../controllers/photoController');
const flash = require('express-flash');
const Photo = require('../models/photoModel');
const upload = multer({
storage: photoController.storage,
fileFilter: photoController.imageFilter
});
// flash messaging
router.use(flash());
router.get('/', (req, res, next)=>{
Photo.find({})
.then((photos)=>{
res.render('photos', {
photos : photos,
flashMsg: req.flash("fileUploadError")
});
})
.catch((err)=>{
if (err) {
res.end("ERROR!");
}
});
});
router.get('/:photoid', (req, res, next)=>{
console.log("finding "+req.params.photoid);
Photo.findOne({'_id': req.params.photoid})
.then((photo)=>{
res.render('updatePhoto', {
photo: photo,
flashMsg: req.flash("photoFindError")
});
}).catch((err)=>{
if (err) console.log(err);
});
});
// I think the error is below!!
router.post('/:photoid', (req, res, next)=>{
console.log("title:", req.body.title)
console.log("description", req.body.description)
Photo.findOne({'_id': req.params.photoid})
.then((photo)=>{
var data = {
title: req.body.title,
description: req.body.description
}
photo.set(data);
photo.save().then(()=>{
res.redirect('/photos');
});
})
.catch((err)=>{
if (err) console.log(err);
});
});
PUG form:
.row
.col-md-6.col-md-offset-3
if flashMsg.length > 0
.alert.alert-danger <strong>FLASH!</strong>#{flashMsg}
p Title: #{photo.title}
p Description: #{photo.description}
p Size: #{photo.size} | Filename: #{photo.originalname} | Uploaded: #{photo.createdAt}| Modified: #{photo.updatedAt}
img(src=photo.imageurl, width="250")
form(method='POST' action="/photos/"+photo._id enctype="multipart/form-data")
div.form-group
label(for='name') Photo Title :
input#name.form-control(type='text', value=photo.title name='title')
div.form-group
label(for='email') Description:
input#email.form-control(type='text', value=photo.description name='description')
div.form-group
label(for='image') Image:
input#name.form-control(type='hidden', name='_id' value=photo._id)
button.btn.btn-primary(type='submit') Update Your Photo
Thanks for your help

You should add to your code the app.use(express.json()) middleware in order to parse automatically the req.body from your request.
const express = require('express');
const router = express.Router();
const app = express();
app.use(express.json()); // Here
const multer = require('multer');
const photoController = require('../controllers/photoController');
const flash = require('express-flash');
const Photo = require('../models/photoModel');
const upload = multer({
storage: photoController.storage,
fileFilter: photoController.imageFilter
});

Related

Requested data didn't came to database and nodejs post text is not showing afterwards submitting

I requested data, but it's neither shows error nor data was added to database.
const express = require("express");
const { hostname } = require("os");
const path = require("path")
const bodyparser = require("body-parser")
const mongoose = require('mongoose');
main().catch(err => console.log(err));
async function main() {
await mongoose.connect('mongodb://localhost/contactdance');
}
const app = express()
const port = 80;
//Defining mongoose scheme
const contactSchema = new mongoose.Schema({
name: String,
phone: String,
email: String,
address: String,
desc: String
});
const Contact = mongoose.model('Contact', contactSchema);
// EXPRESS SPECIFIC STUFF
app.use('/static', express.static('static')) // For serving static files
app.use(express.urlencoded())
// PUG SPECIFIC STUFF
app.set('view engine', 'pug') // Set the template engine as pug
app.set('views', path.join(__dirname, 'view')) // Set the views directory
//end point
app.get('/', (req, res)=>{
const params ={ }
res.status(200).render('home.pug', params);
})
app.get('/contact', (req, res)=>{
const params ={ }
res.status(200).render('contact.pug', params);
})
app.post('/contact', (req, res)=>{
var myData = new Contact(req.body);
myData.save().then(()=>{
res.send("This item has been saved to the database")
}).catch(()=>{
res.status(400).send("item was not saved to the databse")
})
})
app.listen(port, ()=>{
console.log(`The application started successfully on port ${port}`);
});
i expected to see text whether it succeeded or not but it didnt happen neither data was added.It didnt showed me error and i am like WTF.when i sew collections database contact was added but not data inside of it.

File upload makes Node JS unresponsive with Multer

I am using Multer Node JS package to upload files to my app sever , the code is basically typical upload file code
const express = require('express')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})
But each time a file is being uploaded the Node server becomes unresponsive and frontend from other request doesnt receive any response from other APIs until the file is uploaded.
Whats the best way to tackle this ?
In your sample code, you must just send a response to the client by res.json() or res.end() :
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
res.status(204).end();
});
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
res.status(204).end();
});
i can give you an example of how i implemented an imageupload in my app. it the code to upload a profile image for a user. i am also using multer middleware so it shoulder be similiar for you:
code is as follows:
// multer middleware:
const multer = require('multer');
const MIME_TYPE_MAP = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/jpg': 'jpg',
};
module.exports = storage = multer.diskStorage({
destination: (req, file, cb) => {
const isValid = MIME_TYPE_MAP[file.mimetype];
let error = new Error('invalid mime type');
if (isValid) {
error = null;
}
cb(error, 'images');
},
filename: (req, file, cb) => {
const name = file.originalname.toLowerCase().split(' ').join('-');
const ext = MIME_TYPE_MAP[file.mimetype];
if (name.includes('.' + ext)) {
cb(null, name)
} else {
cb(null, name + '.' + ext);
}
},
});
and here the code in the service handling the fileupload
// profile service in backend written in express
exports.uploadImage = (req, res, next) => {
const url = req.protocol + '://' + req.get('host');
profileRepository
.findOne({ _id: req.params.id })
.then((response) => {
const fetchedUser = response;
fetchedUser.imagePath = url + '/images/' + req.file.filename;
profileRepository
.updateOne({ _id: req.params.id }, fetchedUser)
.then((response) => {
return res.status(200).json({
message: 'profileimage updated',
});
})
.catch((error) => {
return res.status(500).json({
message: 'uploading image failed',
});
});
})
.catch((error) => {
return res.status(404).json({
message: 'fetching user failed',
});
});
};
then i use the middleware in my profile routes file like this:
// profile.routes.js
const express = require('express');
const ProfileController = require('./profileController');
const checkAuth = require('../middleware/checkAuth');
const router = express.Router();
const fileStorage = require('../middleware/fileStorage');
const multer = require('multer');
// imageUpload
router.post('/user/image/:id', checkAuth, multer({storage: fileStorage}).single('image'), ProfileController.image);
my Controller then calls the service function with the actual business logic like this:
// profile.controller.js
const profileService = require('./profileService');
exports.image = (req, res, next) => {
return profileService.uploadImage(req, res);
};
and finally my route is used by my app.js file like this:
// app.js
const express = require('express');
const profileRoutes = require('./profile/profileRoutes');
const app = express();
// set images path for saving images on server
app.use('/images', express.static(path.join('images')));
app.use('/api', profileRoutes);
module.exports = app;
i hope i was able to point you in the right direction with my example

Image Not Rendering in ejs

I have a simple app which gets heading, description and image from the user multer handle the image uploading part and I get the images in static folder called public and its sub folder uploads. Then it is toed in the database. I find it in database and try to render the image but image is not rendering. Although it is present in uploads folder but it is not rendering.
Here is My code.
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const mongoose = require("mongoose");
const multer = require("multer");
const fs = require("fs");
const path = require("path");
//APP use
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname+"./public/"));
//Multer Setup
const storage = multer.diskStorage({
destination: "./public/uploads/",
filename: (req, file, cb) => {
cb(null, file.fieldname + '_' + Date.now()+path.extname(file.originalname));
}
});
const upload = multer({ storage: storage }).single("img");
//Mongoose Setup
mongoose.connect('mongodb://localhost:27017/project-1', {useNewUrlParser: true, useUnifiedTopology: true}).then(console.log("Successfully connected to the server"));
//Routes
app.get("/", (req, res)=>{
BlogModel.find({}, function(err, foundItem){
if(err){
console.log(err);
}else{
console.log(foundItem);
res.render("home", {foundItem : foundItem});
}
})
});
app.get("/creat", (req, res)=>{
res.render("creat");
});
app.post("/creat", upload ,(req, res)=>{
const data = new BlogModel({
heading: req.body.name,
desc: req.body.desc,
img: req.file.filename
});
data.save((err)=>{
if(!err){
res.redirect("/");
}else{
console.log(err);
}
});
console.log("Successfully Submited The Form");
});
//Database Schema
const Blogschema = new mongoose.Schema({
heading: String,
desc: String,
img: String
});
//Database Model
const BlogModel = new mongoose.model("Image", Blogschema);
//Listen On Port 3000
app.listen(3000, ()=>{
console.log("Listening on port 3000");
});
<%- include('partials/header'); -%>
<% foundItem.forEach(function(item){ %>
<h1><%= item.heading %></h1>
<p><%=item.desc%></p>
<img src="./uploads/<%=item.img%>" alt="image">
<%})%>
<%- include('partials/footer'); -%>
Here it is stored in the public Folder inside Uploads
Here is the error.
Sorry if the code is to long.
Try adding 'public' for static folder name
app.use(express.static("public"));
Or if you want to use __dirname,
app.use(express.static(path.join(__dirname, 'public')))

MongoDB Returns Empty Error Object when Making POST Request

I'm currently learning about APIs. I'm using Dev Ed's video on a RESTful MERN API. I set up my routes and I could successfully connect to my MongoDB database. However, when attempting to call save() on a post to the DB, I was returned my error message, a JSON object with a message containing the err, but my err object was completely empty.
posts.js:
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
router.get('/', (req, res) => {
res.send('We are on /posts!');
});
router.post('/', (req, res) => {
const post = new Post({
title: req.body.title,
desc: req.body.desc,
});
post.save()
.then(data => {
res.json(data);
})
.catch(err => {
res.json({ message: err });
});
});
module.exports = router;
app.js:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const app = express();
const PORT = 8080;
app.use(bodyParser.json());
// Import Routes ------------------------
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
// ROUTES --------------------------------
app.get('/', (req, res) => {
res.send('We are home!');
});
mongoose.connect(
process.env.DB_CONN,
{ useNewUrlParser: true },
() => {
console.log('Succesfully connected to DB!')
});
app.listen(PORT);
Post.js (schema):
const mongoose = require('mongoose');
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true,
},
desc: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
}
});
module.exports = mongoose.model('Posts', PostSchema);
My POST request and response (Postman):
In my code, I am attempting to send the new Post to my DB, but instead I get an error, an empty one. I either need to figure out how to view my error correctly (so that's it's not empty) or the larger problem: why my POST request is failing.
Again, I am learning about APIs, this is my very first time writing one. If there's anything I missed (like other code that you would need) or if there's something I should be doing differently, please, let me know! Thank you in advance!
use status when you want to use res like this:
for success result
res.status(200).json(data);
for .catch
res.status(500).json({ message: err });
but I prefer use async/await with try/cacth like this:
router.post('/', async(req, res) => {
const post = new Post({
title: req.body.title,
desc: req.body.desc,
});
try {
let data = await post.save()
res.status(200).json(data)
} catch (error) {
res.status(500).json({ message: error});
}
});
check the documentation of promises in mongnoos
check the connection of mongoose like this:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const app = express();
const PORT = 8080;
app.use(bodyParser.json());
// Import Routes ------------------------
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
// ROUTES --------------------------------
app.get('/', (req, res) => {
res.send('We are home!');
});
runMongoose()
app.listen(PORT);
async function runMongoose(){
try {
await mongoose.connect(
process.env.DB_CONN,
{ useNewUrlParser: true }
);
console.log("mongodb is OK");
} catch (error) {
console.log("mongodb Warning", error);
}
}
if Succesfully connected to DB! printed mongoose connection is OK
the problem is that you added
{ useNewUrlParser: true }
remove that and it's gonna work fine ;)

Getting frequent error while passing data from form to a URL in NodeJS the error is cannot post /urlname

this is my from page where I post to a URL articles but it gives me error that cannot POST/URL name
every time I want to save a new article it gives me same error cannot post/URL name
<form action="/routes/articles" method="post">
//here I simply used a partials!
{{>form}}
</form>
this is code where I get data through post method that is mentioned and then it is saved to the database const express = require('express');
const router = express.Router();
const Article = require("../model/schema")
router.get('/', (req, res) => {
res.send('hey !!');
});
router.get('/new', (req, res) => {
res.render('articleGenerator');
});
router.get("/:id",(req,res)=>{
})
router.post("/",async(req,res)=>{
const newArticle = new Article({
title:req.body.title,
description:req.body.description,
markdown:req.body.markdown
})
//this code saves new article that is send from form page mentioned above
try {
newArticle = await newArticle.save();
res.redirect(`/articles/${newArticle.id}`)
} catch (error) {
res.render("/articleGenerator",{articles:newArticle});
}
})
this is my main file that i run Note that I have exported one route articlesjs that saves data.
module.exports = router;
const express = require('express');
const app = express();
const mongoose = require("mongoose");
this is for data base mongoose//
mongoose.connect("mongodb://127.0.0.1:27017/blogging-site",{
useNewUrlParser:true,
useUnifiedTopology:true,
useCreateIndex:true
})
//here i get the routes of page that is saving the data
const theRoutes = require('./routes/articles')
app.use('/theroutes', theRoutes);
app.set('view engine', 'hbs');
app.get('/', (req, res) => {
res.render('index');
});
app.listen(3000, () => {
console.log('server is up and running!!');
});

Categories

Resources