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();
});
});
Related
I have two forms (signup form and an other form XYZ) in one Reactjs/Nodejs project.
How to post the two forms data to two different databases table, each one autonome ?
PS: I'm new in Nodejs, Thanks in advance.
My codes so far:
server.js:
const express = require('express')
const mongoose = require('mongoose')
const bodyparser = require('body-parser')
const FormRoute = require('./routes/FormRoute')
//database
mongoose.connect('mongodb://localhost:27017/form', { useNewUrlParser: true, useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (err) => {
console.log(err)
})
db.once('open', () => {
console.log("Database connection established!")
})
//app
const app = express()
app.use(bodyparser.urlencoded({ extended: true }))
app.use(bodyparser.json())
//cors
const cors = require('cors')
app.use(cors())
//server run
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
app.use('/api/form', FormRoute);
FormModel.js: (this is signup form model)
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const formSchema = new Schema({
title: {
type: String
},
fname: {
type: String
},
lname: {
type: String
},
email: {
type: String
},
phoneNumber: {
type: String
},
cv: {
type: String
},
coverLetter: {
type: String
},
score: {
type: Number,
default: 0
}
}, { timestamps: true })
const form = mongoose.model('form', formSchema)
module.exports = form
FormXYZModel.js: (this is XYZ form model)
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const formXYZSchema = new Schema({
name: {
type: String
},
email: {
type: String
},
password: {
type: String
},
dateOfBirth: {
type: Date
},
role: {
type: String,
default: user
}, { timestamps: true })
const formXYZ = mongoose.model('formXYZ', formSchema)
module.exports = formXYZ
I followed a tutorial and tried to implement some code from this repo https://github.com/ArjunAranetaCodes/MoreCodes-Youtube/tree/master/mern-mysql-login-reg. It takes a user's registration information and stores it in a database.
When I put in http://localhost:5000/users/register in postman I get a Cannot GET /users/register and I don't know why.
I don't know if its a problem with the database or not. I should be able to reach /users/register though shouldn't I?
server.js
const cors = require('cors');
const bodyParser = require('body-parser');
const express = require('express');
const port = process.env.PORT || 5000;
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }))
const Users = require('./routes/Users');
app.use('/users', Users)
app.listen(port, () => {
console.log('SERVER RUNNING ON PORT: ' + port);
});
database/db.js
const Sequelize = require("sequelize")
const db = {}
const sequelize = new Sequelize("accounts", "root", "password", {
host: "localhost",
dialect: "mysql",
operatorAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
})
db.sequelize = sequelize
db.Sequelize = Sequelize
module.exports = db
models/User.js
const Sequelize = require('sequelize')
const db = require('../database/db.js')
module.exports = db.sequelize.define(
'user',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
email: {
type: Sequelize.STRING
},
username: {
type: Sequelize.STRING,
},
password: {
type: Sequelize.STRING,
},
name: {
type: Sequelize.STRING,
},
datetime: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
}
},
{
timestamps: false
}
)
routes/Users.js
const express = require('express')
const users = express.Router()
const cors = require('cors');
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt');
const User = require("../models/User")
users.use(cors());
process.env.SECRET_KEY = 'secret'
users.post('/register', (req, res) => {
const today = new Date().toDateString()
const userData = {
email: req.body.email,
username: req.body.username,
password: req.body.password,
name: req.body.name,
datetime: today
}
User.findOne({
where: {
email: req.body.email
}
})
.then(user => {
if (!user) {
bcrypt.hash(req.body.password, 10, (err, hash) => {
userData.password = hash
User.create(userData)
.then(user => {
res.json({ status: user.email + 'REGISTERED' })
})
.catch(err => {
res.send('ERROR: ' + err)
})
})
} else {
res.json({ error: "USER ALREADY EXISTS" })
}
})
.catch(err => {
res.send('ERROR: ' + err)
})
})
module.exports = users
I am using ORM and i am in new in this. I searched alot but nothing found. Please help me to figure out the error
Here is the error
And Here is the Database connection
const Sequelize = require("sequelize");
const config = require("../../config/config.json");
const sequelize = new Sequelize(
config.database,
config.username,
config.password,
{
host: "127.0.0.1",
port: "80",
dialect: "mysql",
operatorAliases: false
}
);
module.exports = sequelize;
global.sequelize = sequelize;
Here is the Model
const Sequelize = require("sequelize");
module.exports = sequelize.define("users", {
id: {
type: Sequelize.INTEGER(11),
allowNull: false,
autoIncrement: true,
primaryKey: true
},
name: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true
},
password: {
type: Sequelize.STRING,
allowNull: false
}
});
Below is the Query
var express = require("express");
var router = express.Router();
var users = require("../src/models/Users");
/* GET home page. */
router.get("/", function(req, res, next) {
users.findAll({
where: {
id: 1
}
});
});
module.exports = router;
Any solution appreciated!
I think the problem isn't with the ORM, instead it is a problem with your connection details.
On what port does your mysql instance running on?
Try the default mysql port: 3306.
Also, try to test the connection to this port using the command telnet 127.0.0.1 PORT
(replace PORT with the port that your mysql instance is running on)
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
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');
});