inserting a new data in db using express post method - node.js

I want to insert a data into db using sequelize express, the below code is working properly, but I want to create a files like controller, config, routes, models like that and postman tool.. I've tried more but I didn't get proper output.
const Sequelize = require('sequelize');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json({ limit: '100mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '100mb',
parameterLimit: 1000000 }));
const sequelize = new Sequelize('ganeshdb', 'root', 'welcome123$',
{
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
const users = sequelize.define('users', {
id: {
primarykey: true,
type: Sequelize.INTEGER,
},
name: Sequelize.STRING,
role: Sequelize.STRING,
email: Sequelize.STRING
});
app.post('/test', function (request, response) {
return users.create({
id: request.body.id,
name: request.body.name,
role: request.body.role,
email: request.body.email
}).then(function (users) {
if (users) {
response.send(users);
} else {
response.status(400).send('Error in insert new record');
}
});
});
app.listen(3001, function () {
console.log('Express server is listening on port 3000');
});

You can do it this way:
https://expressjs.com/en/starter/generator.html
Example:
npm install express-generator -g
express --view=pug myapp
And you can see more https://solidgeargroup.com/clean-architecture-in-nodejs

Related

My postgres tables are not showing after I defined my models with Sequelize

//db.config.js
module.exports = {
HOST: 'localhost',
USER: 'postgres',
PASSWORD: '123',
DB: 'capital-greek',
dialect: 'postgres',
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000,
},
};
//server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
let corsOptions = {
origin: 'http://localhost:8081',
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(bodyParser.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// database
const db = require('./app/models');
const Role = db.role;
// db.sequelize.sync()
// force: true will drop the table if it already exists
db.sequelize.sync({ force: true }).then(() => {
console.log('Drop and Resync Database with { force: true }');
initial();
});
// simple route
app.get('/', (req, res) => {
res.json({ message: 'Welcome to bezkoder application.' });
});
// routes
require('./app/routes/auth.routes.js')(app);
require('./app/routes/users.routes.js')(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
function initial() {
Role.create({
id: 1,
name: 'user',
});
Role.create({
id: 2,
name: 'moderator',
});
//models/index.js
const config = require('../config/db.config.js');
const Sequelize = require('sequelize');
const sequelize = new Sequelize(config.DB, config.USER, config.PASSWORD, {
host: config.HOST,
dialect: config.dialect,
operatorsAliases: 0,
pool: {
max: config.pool.max,
min: config.pool.min,
acquire: config.pool.acquire,
idle: config.pool.idle,
},
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.user = require('../models/user.model.js')(sequelize, Sequelize);
db.role = require('../models/role.model.js')(sequelize, Sequelize);
db.role.belongsToMany(db.user, {
through: 'user_roles',
foreignKey: 'roleId',
otherKey: 'userId',
});
db.user.belongsToMany(db.role, {
through: 'user_roles',
foreignKey: 'userId',
otherKey: 'roleId',
});
db.ROLES = ['user', 'admin', 'moderator'];
module.exports = db;
After going through the trouble of getting my postgres server running, I now have a different issue with not being able to see my tables generated in to my database. I defined my models with Sequelize, only thing I haven't done yet was create a seed file for my database so that way I can see what I have. I'm connected to the database that I created on the command line. When I type the command "\dt" inside postgres, I get back "Did not find any relations." Any help would be greatly appreciated , I've been stuck in this process for a long time.

How to fix post method error using ExpressJs and MongoDB

I'm new in Express.js,MongoDb and mongoose, I have created HTTP request methods, but when running the Post method, nothing is done (nothing saved in the database), and postman still loading and it stops only when I cancel. I want to know what's wrong in my code, thank you .
router.post("/v1/department", async (req, res) => {
try {
const request = req.body
const department = new Department(request)
await department.save()
res.status(200).send(department)
} catch (error) {
res.status(500).send(error)
}
});
This is my model
const mongoose = require("mongoose");
const validator = require('validator')
const Department = mongoose.model('Department', {
name: {
type: String,
required: true,
}
,
email: {
type: String,
required: true,
trim: true,//
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Invalid email!')
}
}
}
,
createdBy: {
type: String,
default: 'SYS_ADMIN'
}
,
updatedBy: {
type: String,
default: 'SYS_ADMIN'
}
,
createdAt: {
type: Date
// ,
// default: Date.getDate()
}
,
updatedAt: {
type: Date
// ,
// default: Date.getDate()
},
isDeleted: {
type: Boolean,
default: false
}
})
module.exports = Department
This is the Index.js
const express = require("express");
const app = express()
const departmentRouter = require("../src/routes/department")
app.use(express.json())
app.use(departmentRouter)
//app.use('/', require('./routes/department'))
const port = process.env.PORT || 5000;//local machine port 3000
app.listen(port, () => (`Server running on local machine port ${port} 🔥`));
The connection to the database is :
const mongoose = require("mongoose");
//Connect to the local mongoDB database for testing the API localy
mongoose.connect('mongodb://127.0.0.1:27017/openemp-api-department', {
useNewUrlParser: true,
useCreateIndex: true
})
You're missing a few things here. Mongoose is never set up in the index.js so there is no connection to the database. This should help you follow step by step
Also in your router you're sending department1 which is never assigned.
If the link doesn't work or you need more information let me know.
For the latest version of Express which is (Express v4.16.0 and higher)
Use this in your server.js file: ----->
const express = require('express');
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
// For Express version less than 4.16.0
// ------------------------------------
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
otherwise your post request will give you error(like not recognizing any names etc)
so make sure to use these according to to express version
index.js file
const mongoose = require("mongoose");
const express = require("express");
const router = express.Router();
const axios = require("axios");
mongoose.connect(
"YourMongoUri",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
const dataSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
age: {
type: Number,
required: true,
},
});
const modelData = mongoose.model("modelData", dataSchema);
router.get("/", (req, res) => {
modelData.find((err, doc) => {
if (err) console.log(err.message);
else {
res.send(doc);
}
});
});
router.post("/", (req, res) => {
const user = new modelData({
name: req.body.name,
age: req.body.age,
});
user.save((err, doc) => {
if (err) return console.log(err);
res.send(doc);
});
});
router.put("/:id", (req, res) => {
const user = modelData.findByIdAndUpdate(
req.params.id,
{
name: req.body.name,
age: req.body.age,
},
(err, doc) => {
if (err) return console.log(err);
res.send(doc);
}
);
});
router.delete("/:id", (req, res) => {
modelData.findByIdAndDelete(req.params.id, (err, doc) => {
if (err) return console.log(err);
res.send(doc);
});
});
module.exports = router;
server.js file
const express = require("express");
const myRouter = require("./index");
const app = express();
const port = 3000;
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
s;
app.use("/myroute", myRouter);
app.listen(port, console.log("listening on port 3000"));

PassportJS JWT Strategy with Node and MySQL not working

I'm having issues with the authentication part of my app. I keep getting this "TypeError: Cannot read property 'fromAuthHeaderAsBearerToken' of undefined at Object." whenever I run my server.js file. It stops me from progressing any further.
Here is my passport.js file
const JWTStrategy = require('passport-jwt').Strategy;
const ExtractJWT = require('passport-jwt').ExtractJWT;
const User = require('../dbConnection/database.js');
const keys = require('./keys.js');
const opts = {
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey: keys.secretOrKey,
};
module.exports = passport => {
passport.use(
new JWTStrategy(opts, (jwt_payload, done) => {
User.findOne( {id: jwt_payload.id} ).then(user => {
if (user) {
return done(null, user);
}
return done(null, false);
})
.catch(err => console.log(err));
})
);
};
User Schema
const mysql = require('mysql2');
const Sequelize = require('sequelize');
// Initiate mysql connection
const connOptions = {
host: 'localhost',
user: 'root',
password: 'dummypassword',
database: 'countdown',
dialect: 'mysql'
};
const sequelize = new Sequelize(connOptions);
// Connect sequelize to the database
sequelize.authenticate()
.then(console.log('Connection has been successfully established'))
.catch(err => console.error('Unable to connect to the database: ', err));
// Create user model
const User = sequelize.define('user', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false
},
firstName: {
field: 'first_name',
type: Sequelize.STRING,
allowNull: false
},
lastName: {
field: 'last_name',
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: false
},
password: {
type: Sequelize.STRING,
allowNull: false
}
}, {
tableName: 'users'
});
module.exports = User;
And also my server.js file
const express = require('express');
const _ = require('lodash');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const users = require('./routes/api/users.js');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/client/public'));
app.use(cors());
// Passport Middleware
app.use(passport.initialize());
// Passport config
require('./config/passport')(passport);
// Routes
app.use('/users', users);
const port = process.env.port || 5000;
app.listen(port, () => {
console.log('Server started on port ' + port);
});
I'm so lost as I literally followed a tutorial that walked this through step by step (https://github.com/rishipr/mern-auth) although it was with MongoDB. I originally didn't use sequelize and thought that might be the issue. So I've refactored it to incorporate sequelize but it didn't solve my issue. Googling didn't help either as no one seems to have this specific issue blocking them from running the server.js file (most people I see are having issues when they make an API call).
Any help is appreciated. Thanks!
The problem is with line number 2 in passport.js file
const ExtractJWT = require('passport-jwt').ExtractJWT;
replace with
consst ExtractJWT= require('passport-jwt').ExtractJwt;
passport-jwt have a ExtractJwt class/method not ExtractJWT. Remember Javascrit is a case sensative language.

Deployed my application successfully on Heroku but does not show other devices

I deployed my application successfully on Heroku. It works fine for my laptop but it does not show on other devices. I don't know what I am doing wrong.
This is my database setup
require("dotenv").config();
const sequelize = require("./node_modules/sequelize");
const con = new sequelize(process.env.DATABASE_URL, {
dialect: "postgres",
protocol: "postgres",
dialectOptions: {
ssl: true
}
});
const Person = con.define("person", {
image: {
type: sequelize.STRING,
allowNull: false
},
firstname: {
type: sequelize.STRING,
allowNull: false
},
lastname: {
type: sequelize.STRING,
allowNull: false
},
email: {
type: sequelize.STRING,
allowNull: false,
validate: {
isEmail: true
}
}
});
const Post = con.define("post", {
title: { type: sequelize.STRING },
content: { type: sequelize.STRING },
personid: { type: sequelize.INTEGER, foreignKey: true }
});
const Parent = con.define("parent", {
father: { type: sequelize.STRING },
mother: { type: sequelize.STRING },
personid: { type: sequelize.INTEGER }
});
con.sync({ force: true });
module.exports = con;
This is my Node js server setup.
const express = require("express");
const app = express();
const graphqlHTTP = require("express-graphql");
const schema = require("./schema");
const cors = require("cors");
const path = require("path");
app.use(cors());
app.use(
"/graphql",
graphqlHTTP({
schema,
pretty: true,
graphiql: true
})
);
app.use(express.static("build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "build", index.html));
});
const port = process.env.PORT || 8081;
app.listen(port, () =>
console.log(`✅ Example app listening on port ${port}!`)
);
This is my Procfile setup
web: node server.js
After reading couple of articles, so far I understand its because of heroku cors settings. But I don't know how to enable cors setting on Heroku.
This is my heroku app link: https://apask.herokuapp.com/
When your deploying on heroku it, you can add this to your server.
const PORT = process.env.PORT || 5000;
const HOST = '0.0.0.0';
const server = app.listen(PORT, HOST, function () {
logger.info("Server running on: " + HOST + ":" + PORT)
process.on('SIGINT', function() {
server.close();
});
});

insert a new record in nodejs using sequelize POST method

I want to insert a new data in database using sequelize express, without query. I am trying so hard but I didn't get the output... If my code is wrong, then give me a code for insert a new record in db using sequelize express.
const Sequelize = require('sequelize');
var express = require('express');
var app = express();
var mysql = require('mysql');
//var request=require('request')
const sequelize = new Sequelize('ganeshdb', 'root', 'welcome123$', {
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
var users = sequelize.define('users', {
id: {
primaryKey: true,
type: Sequelize.INTEGER,
},
name: Sequelize.STRING,
role: Sequelize.STRING,
email: Sequelize.STRING
});
app.post('/test', function (request, response) {
return users.create({
name: request.body.name,
role: request.body.role,
email: request.body.email
}).then(function (users) {
if (users) {
response.send(users);
} else {
response.status(400).send('Error in insert new record');
}
});
});
app.listen(3000, function () {
console.log('Express server is listening on port 3000');
});
You should use body-parser
https://www.npmjs.com/package/body-parser
Example use body-parser:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
Example:
const Sequelize = require('sequelize');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json({ limit: '100mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '100mb', parameterLimit: 1000000 }));
const sequelize = new Sequelize('test_01', 'root', 'root', {
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
const users = sequelize.define('users', {
id: {
primaryKey: true,
type: Sequelize.INTEGER,
},
name: Sequelize.STRING,
role: Sequelize.STRING,
email: Sequelize.STRING
});
app.post('/test', function (request, response) {
return await users.create({
id: request.body.id,
name: request.body.name,
role: request.body.role,
email: request.body.email
}).then(function (users) {
if (users) {
response.send(users);
} else {
response.status(400).send('Error in insert new record');
}
});
});
app.listen(3001, function () {
console.log('Express server is listening on port 3000');
});

Resources