CRUD express.JS with mysql issue - node.js

I have this as configuration of my Express index.js:
var express = require('express');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var router = express.Router();
//connection database
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'learn'
});
connection.connect(function (err){
if (err) throw err;
console.log('Database connected . . . \n\n');
});
router.get('/', function(req, res, next) {
var sql = 'SELECT * FROM `test`';
connection.query(sql, function(err, rows, field){
if (err) throw err;
res.render('index', {
data: rows
})
});
});
router.get('/add', function (req, res, next){
res.render('add_costumer', {title: 'Update'});
});
router.post('/add', function (req, res){
var input = req.body;
var data = {
name : input.name,
email : input.email,
phone : input.number_phone
};
connection.query('INSERT INTO `test` SET ?', data, function(err,rows){
if(err) throw err;
console.log("Error inserting : %s ",err );
res.redirect('/');
});
});
router.get('/update', function (req, res, next){
res.render('update', {judul: 'Add'});
});
module.exports = router;
But still when I ask for req.body.something in my routes I get some error pointing Cannot read property 'name' of undefined. Here is an example of a route that uses req.body and this picture of the printing code :
output like this
Any clue?

It looks like you are requiring body-parser but not actually using it.
Depending on what kind of content you are accepting you should do:
app.use(bodyParser.json()); // where app is your express app
app.use(bodyParser.urlencoded({ extended: true});

Related

Function.Module._resolveFilename (module.js:547:15) at Function.Module._load

I am getting following error
Function.Module._resolveFilename (module.js:547:15) at Function.Module._load (module.js:474:25) at Module.require (module.js:596:17) at require (internal/module.js:11:18) at Object. (C:\Users\u8ser\Desktop\Todo\server.js:25:1) at Module._compile (module.js:652:30) [nodemon] app crashed - waiting for file changes before starting
PFB source code for your ref.
My server.js file
var express = require("express");
var app = express();
var mongoose = require("mongoose");
var methodOverride = require("method-override");
var port = process.env.PORT || 8080;
var database = require('./config/database');
var morgan = require("morgan");
var bodyParser = require("body-parser");
mongoose.connect('mongodb://localhost:27017', function(err){
if (err){
console.log(err);
}else{
console.log("Connected to DB");
}
});
app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type : 'application/vnd.api+json'}));
app.use(methodOverride());
require('./models/routes')(app);
app.listen(port);
console.log("App listining to port" + port);
My routes.js file
var Todo = require('./models/todo');
module.exports = function(app){
app.get('/api/todos', function(req, res){
Todo.find(function(err, todos){
if (err)
res.send(err)
res.send(todos)
});
});
// create todo and send back all todos after creation
app.post('/api/todos', function(req, res){
// create a todo, information comes from AJAX request from Angular
Todo.create({
text : req.body.text,
done : false
}, function(err, todo) {
if (err)
res.send(err);
//get and return all the todos after you create another
Todo.find(function(err, todos){
if (err)
res.send(err)
res.json(todos);
});
});
});
//delete a todo
app.delete('/api/todos/:todo_id', function(req, res){
Todo.remove({
_id : req.params.todo_id
}, function(err, todo){
if (err)
res.send(err);
//get and return all the todos after you create another
Todo.find(function(err, todos){
if (err)
res.send(err)
res.json(todos);
});
});
});
// server.js
// application -------------------------------------------------------------
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
};
Kindly visit this github link for full source code.
The issue is in server.js file. Try with below updated solution
Server.js:
var express = require("express");
var app = express();
var mongoose = require("mongoose");
var methodOverride = require("method-override");
var port = process.env.PORT || 8080;
var database = require('./config/database');
var morgan = require("morgan");
var bodyParser = require("body-parser");
var routes = require('./app/models/routes');
mongoose.connect('mongodb://localhost:27017', function(err){
if (err){
console.log(err);
}else{
console.log("Connected to DB");
}
});
app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type : 'application/vnd.api+json'}));
app.use(methodOverride());
app.use('/api', routes); // you should add base path like this and assign routes
app.listen(port);
console.log("App listining to port" + port);
And in routes.js file remove /api because we added /api as base path in server.js
var Todo = require('./todo');
module.exports = function(app){
app.get('/todos', function(req, res){
Todo.find(function(err, todos){
if (err)
res.send(err)
res.send(todos)
});
});
// create todo and send back all todos after creation
app.post('/todos', function(req, res){
// create a todo, information comes from AJAX request from Angular
Todo.create({
text : req.body.text,
done : false
}, function(err, todo) {
if (err)
res.send(err);
//get and return all the todos after you create another
Todo.find(function(err, todos){
if (err)
res.send(err)
res.json(todos);
});
});
});
//delete a todo
app.delete('/todos/:todo_id', function(req, res){
Todo.remove({
_id : req.params.todo_id
}, function(err, todo){
if (err)
res.send(err);
//get and return all the todos after you create another
Todo.find(function(err, todos){
if (err)
res.send(err)
res.json(todos);
});
});
});
// server.js
// application -------------------------------------------------------------
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});
};
The schema should be created below way but what you are doing is wrong
var mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BlogPost = new Schema({
text : String,
done : Boolean
});
module.exports = mongoose.model('Todo', BlogPost);
I think you wrote bad path to routes.js file.
Try
require('./app/models/routes')(app);
instead of
require('./models/routes')(app);

GET /signup - - ms - -(both get and post not working, it was a while idk whats wrong)

1.GET /signup - - ms - -(both GET and POST not working, it was a while I don’t know whats wrong)
2. please check below code
3.server.js. This this the app code that you have requested.Kindly go through it. Also the value for link is replaced by word link as it is private.
4. There are two files in this. Server.js and user.js kindly check it out.
var router = require("express").Router();
var User = require("../models/user.js");
router.get("/signup", function(req, res){
res.send("hello");
});
router.post('/signup', function(req, res, next){
var user = new User();
user.profile.name = req.body.name;
user.email = req.body.email;
user.password = req.body.password;
User.findOne( { email : req.body.email }, function(err, existingUser) {
if(existingUser){
console.log(req.body.email + "already exists");
return res.redirect("/signup");
}
else{
user.save(function(err, user){
if(err) return next(err);
res.send("New user has been added");
});
}
});
});
module.exports = router;
//server.js code
var express = require("express");
var morgan = require("morgan");
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var User = require("./models/user.js");
var ejs = require("ejs");
var engine = require("ejs-mate");
var app = express();
mongoose.connect('link', function(err){
if(err){
console.log(err);
}
else{
console.log("connected to database");
}
});
//middle ware
app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.engine("ejs", engine);
app.set("view engine", "ejs");
var mainRoutes = require("./routes/main.js");
var userRoutes = require("./routes/user.js");
app.use(mainRoutes,function(err){
if(err){
console.log("error is here")
}
});
app.use(userRoutes, function(err){
if(err){
console.log("error is here in 2" );
}
});
//listen to port 3000
app.listen(3000, function(err){
if(err) throw err;
console.log("Server has started");
});
removed the call back function from app.use() and it worked.

Express.js nested routes without parameters

I have a Express server resolving GET /companies/:id/populate/. Now, I would like to setup GET /companies/populate/ (without the :id). However, I can't make this route to work. If I try, for example, GET /companies/all/populate/, it works, so it seems the pattern for an Express route is path/:key/path/:key.
Is this true? Thanks!
Edit: Adding code.
server.js
'use strict';
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var mongoUri = 'mongodb://localhost:27017';
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', function() {
throw new Error('Unable to connect to database at' + mongoUri);
});
// runs Express
var app = express();
// uses Cors
app.use(cors());
// uses bodyParser
app.use(bodyParser.json());
// requires Mongo models
require('./models');
// includes routes.js, passing the object 'app'
require('./routes')(app);
// listens for connections on port 3000
app.listen(3000, function() {
console.log("Express started on Port 3000");
});
routes.js
module.exports = function(app) {
// thumbs up if everything is working
app.get('/', function(req, res, next) {
res.send('👍');
console.log('Server Running');
res.end();
});
// companies
var companies = require('./controllers/companies');
app.get('/companies', companies.findAll);
app.get('/companies/:id', companies.findById);
app.get('/companies/:id/populate', companies.populate);
app.get('/companies/populate', companies.populateAll);
app.post('/companies', companies.add);
app.patch('/companies/:id', companies.patch);
app.delete('/companies/:id', companies.delete);
};
/controllers/companies.js
var mongoose = require('mongoose');
Company = mongoose.model('Company');
// GET /companies
// status: works, needs error handling
exports.findAll = function(req, res) {
Company.find({}, function(err, results) {
return res.send(results);
});
};
// GET /companies/:id
// status: works, needs to check error handling
exports.findById = function(req, res) {
var id = req.params.id;
Company.findById(id, function(err, results) {
if (results) res.send(results);
else res.send(204);
});
};
// POST /companies
// status: works, needs error handling
exports.add = function(req, res) {
Company.create(req.body, function(err, results) {
if (err) {
return console.log(err)
} else {
console.log('company created');
}
return res.send(results);
});
};
// PATCH /companies/:id
// status: works, needs error handling
exports.patch = function(req, res) {
var id = req.params.id;
var data = req.body;
Company.update( { '_id' : id }, data, function(err, numAffected) {
if (err) return console.log(err);
return res.send(200);
});
};
// DELETE /companies/:id
// status: works, needs error handling, make sure that we are sending a 204 error on delete
exports.delete = function(req, res) {
var id = req.params.id;
Company.remove({ '_id': id }, function(results) {
console.log('deleted ' + id); // tester
return res.send(results);
});
};
// GET /companies/:id/populate
exports.populate = function(req, res) {
var id = req.params.id;
Company
.findOne({ _id: id })
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};
// GET /companies/populate
exports.populateAll = function(req, res) {
Company
.find({})
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};

MEAN stack application - getting details of a single user, querying by username

I have built an API to GET and POST values into a database(MongoDB) using NodeJS and Express.
I am able to get the total list of users stored on my database (localhost:3000/user)
But I want to get a single users details by either entering the userID or userName(localhost:3000/user/:username)(localhost:3000/user/:userID)
I am able to get a single users details through ObjectID(localhost:3000/user/:id)
App.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
//var routes = require('./routes/index');
//var users = require('./routes/users');
//Router for developers
var developer = require('./routes/developer');
//Router for TvShows
var tvshow = require('./routes/tvshow');
//Router for TvShows
var user = require('./routes/user');
//Router for TvShowRating
var tvshowrating = require('./routes/tvshowrating');
//Router for TvShowEpisodes
var tvshowepisodes = require('./routes/tvshowepisodes');
//Router for TvShowNewsFeed
var tvshownewsfeed = require('./routes/tvshownewsfeed');
//Router for TvShowSeason
var tvshowseason = require('./routes/tvshowseason');
//Router for TvShowRatingUser
var tvshowratinguser = require('./routes/tvshowratinguser');
// load mongoose package
var mongoose = require('mongoose');
// Use native Node promises
mongoose.Promise = global.Promise;
// connect to MongoDB
//mongoose.connect('<string>')
//mongoose.connect('mongodb://localhost/televisionary-api')
.then(() => console.log('connection succesful'))
.catch((err) => console.error(err));
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//Registering routers
app.use('/developer', developer);
app.use('/tvshow', tvshow);
app.use('/user', user);
app.use('/tvshowrating', tvshowrating)
app.use('/tvshowepisodes', tvshowepisodes)
app.use('/tvshownewsfeed', tvshownewsfeed)
app.use('/tvshowseason', tvshowseason)
app.use('/tvshowratinguser', tvshowratinguser)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
. routes/User.js
var express = require('express');
var router = express.Router();
var User = require('../models/User.js');
/* GET /user listing. */
router.get('/', function(req, res, next) {
User.find(function (err, user) {
if (err) return next(err);
res.json(user);
});
});
/* POST /user */
router.post('/', function(req, res, next) {
User.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* GET /user/id */
router.get('/:id', function(req, res, next) {
User.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* PUT /user/:id */
router.put('/:id', function(req, res, next) {
User.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* DELETE /user/:id */
router.delete('/:id', function(req, res, next) {
User.findByIdAndRemove(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
module.exports = router;
. models/User.js
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
userId:Number,
userName: String,
userEmail: String,
userPassword: String,
userCreatedDateTime: Date,
userWatchList: [
{
watchListItemId:Number,
tvShowId: Number,
tvShowSeasonId: Number,
tvShowEpisodeId: Number,
tvShowAddedDateTime: Date
}
],
userFavouriteList: [
{
favouriteId:Number,
tvShowId: Number,
tvShowFavouritedDateTime: Date
}
],
userRatings: [
{
tvShowUserRatingId:Number,
tvShowId: Number,
tvShowSeasonId: Number,
tvShowEpisodeId: Number,
tvShowRatedDateTime: Date,
tvShowRating: Number,
tvShowUserTags:[String]
}
]
});
module.exports = mongoose.model('User', userSchema);
If you want to get user details by entering username or userid in one service then modify your service with this:
router.get('/:keyword', function(req, res, next){
User.findOne({$or:[{userName: req.params.keyword}{userId:req.params.keyword}]},
function (err, post) {
if (err) return next(err);
res.json(post);
});
});
You can use findOne method to get a specific user from a database.
router.get('/user/:username', function(req, res, next) {
User.findOne({userName: req.params.username}, function(err, user) {
if(err)
console.log(err);
else
//do something with user
})
});
Same for fetching user using userId.

PUT and DELETE - RESTful API Express MongoDB Mongoose

First time posting. I'm building a blog site and using Node.js, Express.js, MongoDB, and Mongoose for my back-end. GET and POST work for getting and creating posts. However, PUT and DELETE are not working when using POSTMAN as I get "Cannot DELETE(PUT) /api/blog". I feel like it's related to routes, particularly when I'm trying to findById (/api/blog/:blog_id).
Server.js
var express = require('express');
var mongoose = require('mongoose');
var port = process.env.PORT || 8080;
var logger = require('morgan');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var app = express();
mongoose.connect('mongodb://127.0.0.1:27017/blog');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
db.once('open', function callback () {
console.log("Scrolls are ready to be written!!!");
});
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.text());
app.use(methodOverride());
app.use(express.static(__dirname + '/client'));
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, HEAD, DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, content-type, Accept');
next();
});
// *Routes*
require('./app/routes.js')(app);
// *App Start*
// http://localhost:8080
app.listen(port);
console.log('Connected to port ' + port);
exports = module.exports = app;
app/routes.js
var Blog = require('./models/blog');
module.exports = function(app) {
// *Server Routes*
// Place API calls here
// Place Authentication routes here
//var express = require('express');
//var router = express.Router();
// *API Routes*
// Uses Mongoose to GET all Blog Posts from database
app.get('/api/blog', function(req, res, next) {
Blog.find(function(err, blog) {
// If error
if (err) return next(err);
//res.send(err);
res.json(blog);
});
});
// Uses Mongoose to POST new Blog Posts in database
app.post('/api/blog', function(req, res) {
Blog.create({
title: req.body.title,
body: req.body.body,
author: req.body.author,
comments: req.body.comments,
likes: req.body.likes,
dislikes: req.body.dislikes,
image: req.body.image,
createdOn: req.body.createdOn
}, function(err, blog) {
if (err)
res.send(err);
Blog.find(function(err, blog) {
if (err)
res.send(err)
res.json({ message: 'Blog Post Created!' });
});
});
});
// Uses Mongoose to GET Blog Post by _id from database
app.get('/blog/:blog_id', function(req, res) {
Blog.findById(req.params.blog_id, function(err, blog) {
if (err)
res.send (err);
res.json(blog);
});
})
// Uses Mongoose to PUT updates for Blog Posts by _id in database
app.put('/blog/:blog_id', function(req, res) {
Blog.findById(req.params.blog_id, function (err, blog) {
if (err) res.send(err);
if (req.body.title) blog.title = req.body.title;
if (req.body.body) blog.body = req.body.body;
if (req.body.author) blog.author = req.body.author;
if (req.body.comments) blog.comments = req.body.comments;
if (req.body.likes) blog.likes = req.body.likes;
if (req.body.dislikes) blog.dislikes = req.body.dislikes;
if (req.body.image) blog.image = req.body.image;
if (req.body.createdOn) blog.createdOn = req.body.createdOn;
blog.save( function (err) {
if (err) send (err);
res.json({message: 'Blog Post Updated!'});
});
});
});
// Uses Mongoose to DELETE Blog Posts by _id in database
app.delete('/blog/:blog_id', function(req, res) {
Blog.remove({
_id: req.params.blog_id
}, function (err, blog) {
if (err) return res.send(err);
res.json({ message: 'Blog Post Deleted'});
});
});
// API's for PUT, POST, DELETE go here
// *Frontend Routes*
// Route to handle all AngularJS requests
app.get('*', function(req, res) {
res.sendfile('./client/views/index.html');
});
};

Resources