i am trying to develop a login system with React,Node,Mysql,Express and Passport but i have encountered this problem. After calling req.login and passing it the userID, when i go to the route where i check for the req.user it says undefined. Here is my code for the server side.
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const session = require("express-session");
const { PORT = 8000 } = process.env;
const bcrypt = require("bcrypt");
const saltRounds = 10;
const cookieParser = require("cookie-parser");
const passport = require("passport");
var LocalStrategy = require('passport-local').Strategy;
const mysql = require("mysql");
/app.options("*", cors());
app.use(cors());
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
// app.use(cookieParser());
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: false
// cookie: { secure: false }
})
);
app.use(passport.initialize());
app.use(passport.session());
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "qwertyhnjkl",
database: "login"
});
connection.connect(err => {
if (err) {
console.error("Error connection to database");
}
else console.log("Database connected");
});
app.get('/',function (req,res){
console.log(req.user);
console.log(req.isAuthenticated())
res.send('hello world')
});
app.post("/register", (req, res) => {
const { name, username, email, password } = req.body;
console.log(req.body);
bcrypt.hash(password, saltRounds, function(err, hash) {
connection.query(
`insert into users(Name,Username,Email,Password) values('${name}','${username}','${email}','${hash}')`,
function(error) {
if (error) console.error(error);
}
);
connection.query("SELECT LAST_INSERT_ID() as userID", (error,results,fields) =>
{
if (error) throw error;
console.log(results)
const userID = results[0].userID;
console.log("userid in query: " + userID);
req.login(userID, function(err) {
if(err) res.send(err);
else{
console.log("req.user in req.login: " + req.user)
console.log("isAuthenticated: "+ req.isAuthenticated())
console.log(req.session )
console.log('Logged in succesfully')
res.send("Logged in succesfully");
}
});
});
});
});
And this is how i handle the form in react:
submitRegister(event) {
event.preventDefault();
const data = this.state.data
axios.post("http://localhost:8000/register", {
name: data.name,
username: data.username,
email: data.email,
password: data.password
})
.then(response => {
console.log(response);
if(response.data){
console.log('Succesful signup');
this.setState({ //redirect to login page
redirectTo: '/'
})
}
}).catch(error => {
console.log("Sign up to server failed");
console.log(error)
});
}
After i request the '/' of the server and check for the session in Application->Cookies->localhost there is no session.
The insertion is well done. I get the username email hashed password in my database. i get the right userID i even get the console.log in serialize function with the right userID(the last one introduced)
req.user in req.login: 47
isAuthenticated: true
Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true },
passport: { user: 47 } }
Logged in succesfully
serialize 47
This is what i get in the console when requesting the route /register from the server. Now when i go for localhost:8000 it says req.user is undefined and isAuthenticated false.
Looks like cors() was the issue here. After removing it and using proxy in package.json solved the issue.
Related
I have a website project with frontend at Netlify and backend at Heroku. Currently, I use express session for recording login information. Just now, with about 40 users logging into the website at the same time, I started to be logged out by Heroku much more frequently and have the error message "Application error" displayed at my server site, like this.
I wonder if the phenomenon is caused by the large number of session information stored in my server after all the users log in at once (since I use express session), but honestly, I don't know how to transform from express to cookie session.
Also, I'm aware that there are quotas for the number of queries sent to the database, in this case ClearDB (MySQL) under Heroku, yet I am not banned from reconnecting with the server after logging in again to Heroku, so it may not be the problem.
How can I fix it? Thanks in advance!
This is my code in index.js (with some unrelated methods left out) in my website's server folder:
const express = require('express')
const mysql = require('mysql')
const cors = require('cors')
const session = require('express-session')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const mysqlStore = require('express-mysql-session')(session);
const port = 3010
const app = express()
app.use(express.json())
app.use(cors({
origin: ["https://xxx.netlify.app"],
methods: ["GET", "POST"],
credentials: true
}))
const options = {
host: "xxx.cleardb.net",
port: 3306,
user: "xxx",
password: "xxx",
database: "heroku_xxx",
createDatabaseTable: true,
schema: {
tableName: 'session_tab',
columnNames: {
session_id: 'session_id',
expires: 'expires',
data: 'data'
}
}
}
const sessionStore = new mysqlStore(options);
app.use(cookieParser())
app.use(bodyParser.urlencoded({extended: true}))
app.set('trust proxy', 1)
app.use(session({
key: "userId",
secret: "nosecret",
store: sessionStore,
resave: true,
saveUninitialized: false,
cookie: {
sameSite: "none",
secure: true,
httpOnly: true,
maxAge: 600 * 1000
}
}))
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "https://xxx.netlify.app");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, DELETE, OPTIONS"
);
res.setHeader('content-type', 'application/json');
next();
});
const db = mysql.createPool({
// create an instance of the connection to the mysql database
host: 'xxx.cleardb.net', // specify host name
user: 'xxx', // specify user name
password: 'xxx', // specify password
database: 'heroku_xxx', // specify database name
})
...
app.post('/login', (req, res) => {
const username = req.body.username
const password = req.body.password
console.log("username");
console.log(username);
console.log("password");
console.log(password);
db.query(
'SELECT * FROM user where username = ? AND password = ?',
[username, password],
(err, result) => {
console.log("result");
console.log(result);
if (err) {
res.send({ err: err })
}
if (result.length) {
req.session.user = result;
console.log("req.session.user (post /login)");
console.log(req.session.user);
if(result[0].role == "student") {
let name = result[0].lastname + result[0].firstname;
console.log(name);
req.session.userfullname = name;
console.log("req.session.userfullname");
console.log(req.session.userfullname);
db.query('SELECT * FROM contact where studentname = ?',
[name],
(err, result) => {
console.log("req.session.userteacherusername");
console.log(req.session.userteacherusername);
req.session.userteacherusername = result[0].username;
})
}
let output = req.session.user + req.session.userfullname + req.session.userteacherusername;
res.send(output);
req.session.save();
} else {
res.send({ message: 'Wrong username or password.' });
}
},
)
})
app.get('/login', (req, res) => {
console.log("req.session.user (get /login)");
console.log(req.session.user);
if(req.session.user) {
res.send({isLoggedIn: true, user: req.session.user})
} else {
res.send({isLoggedIn: false})
}
})
...
app.post('/logout', (req, res) => {
req.session.destroy(
function(err){
if(err){
res.send(err)
}else{
res.send("successfully logged out.")
}
}
);
})
...
app.listen(process.env.PORT || port, () => {
console.log('Successfully Running server at ' + port + '.')
});
Made a Question a few days ago on here, thought I had it figured out, even accepted the answer, because it was right regardless. but now I have the Same issue, same error.
Heres the Error.
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:558:11)
at ServerResponse.header (/Users/apple/Documents/Web Dev/collab/Backend/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/Users/apple/Documents/Web Dev/collab/Backend/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/Users/apple/Documents/Web Dev/collab/Backend/node_modules/express/lib/response.js:267:15)
at /Users/apple/Documents/Web Dev/collab/Backend/routes/index.js:90:23
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
Heres Index.js. Line 90 is at the very bottom,
# router.get("/", isAuth, (req, res)
const router = require("express").Router();
const passport = require("passport");
const bodyParser = require("body-parser");
const genPassword = require("../lib/passwordUtils").genPassword;
const connection = require("../config/database");
const mongoose = require("mongoose");
const User = mongoose.models.User;
const isAuth = require("./authMiddleware").isAuth;
// cors is needed with router.use else you have to put routes on the app.js
const cors = require("cors");
router.use(cors({ origin: "http://localhost:3001", credentials: true }));
// const isAdmin = require("./authMiddleware").isAdmin;
router.use(bodyParser.urlencoded({ extended: false }));
/**
* -------------- Post ROUTES ----------------
*
*/
router.post("/login", (req, res, next) => {
passport.authenticate("local", (err, user, info) => {
if (err) {
throw err;
} else if (!user) {
res.send("No User Exists");
} else {
req.logIn(user, (err) => {
if (err) throw err;
res.send(user);
return;
// console.log(req.user);
});
}
})(req, res, next);
});
router.post("/register", (req, res) => {
const saltHash = genPassword(req.body.repeatPassword);
const salt = saltHash.salt;
const hash = saltHash.hash;
const newUser = new User({
username: req.body.firstInput,
fName: "",
lName: "",
title: "",
hash: hash,
salt: salt,
});
newUser.save().then((user) => {});
res.sendStatus(200);
});
/**
* -------------- GET ROUTES ----------------
*
*/
router.post("/user", (req, res) => {
const fName = req.body.firstInput;
const lName = req.body.secondInput;
const title = req.body.repeatPassword;
const user = req.session.passport.user;
User.updateOne(
{ _id: user },
{ fName: fName, lName: lName, title: title },
function (err, result) {
if (err) {
res.sendStatus(401);
console.log(err);
} else {
res.sendStatus(200);
}
}
);
});
router.get("/", isAuth, (req, res) => {
const userMap = {};
User.find({}, function (err, users) {
users.forEach(function (user) {
userMap[user._id] = user;
});
return userMap;
})
.then((response) => {
res.status(200).json({ user: req.user, auth: true, response });
return;
})
.catch((err) => console.log(err));
});
module.exports = router;
Heres App.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const crypto = require("crypto");
const routes = require("./routes");
const isAuth = require("./routes/authMiddleware").isAuth;
const connection = require("./config/database");
const cors = require("cors");
app.use(cors({ origin: "http://localhost:3001", credentials: true }));
const User = mongoose.models.User;
const bodyParser = require("body-parser");
const MongoStore = require("connect-mongo")(session);
require("dotenv").config();
app.use(express.json());
// app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.urlencoded({ extended: true }));
const sessionStore = new MongoStore({
mongooseConnection: mongoose.connection,
collection: "sessions",
});
app.use(
session({
secret: "zdfbdaf",
resave: true,
saveUninitialized: true,
store: sessionStore,
cookie: {
cookie: { secure: false },
maxAge: 1000 * 60 * 60 * 24,
},
})
);
require("./config/passport");
app.use(passport.initialize());
app.use(passport.session());
app.use("/", routes);
app.listen(3000);
heres authMiddleware.js
module.exports.isAuth = (req, res, next) => {
if (req.isAuthenticated()) {
next();
// res.status(200).json({ user: req.user, auth: true });
} else {
res.status(401).json({ auth: false });
}
};
// module.exports.isAdmin = (req, res, next) => {
// if (req.isAuthenticated() && req.user.admin) {
// next();
// } else {
// res.status(401).json({ msg: 'You are not authorized to view this resource because you are not an admin.' });
// }
// }
Heres passport.js
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const connection = require("./database");
const mongoose = require("mongoose");
const User = mongoose.models.User;
const validPassword = require("../lib/passwordUtils").validPassword;
const cors = require("cors");
passport.use(cors({ origin: "http://localhost:3001" }));
const customFields = {
usernameField: "username",
passwordField: "password",
};
passport.use(
new LocalStrategy(customFields, (username, password, done) => {
User.findOne({ username: username })
.then((user) => {
if (!user) {
console.log("No user");
return done(null, false);
} else {
const isValid = validPassword(password, user.hash, user.salt);
if (isValid) {
console.log("Logged in");
return done(null, user);
} else {
console.log("Wrong Password");
return done(null, true);
}
}
})
.catch((err) => {
done(err);
});
})
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
})
.then((user) => {
done(null, user);
})
.catch((err) => done(err));
});
It only crashes half the time, kind of? It works at first, until you refresh the page. I am at a loss. Had someone in the discord also not know the issue. I'm begging for some help here. I'm losing my mind.
its because you are calling done twice once after finding the user
and second after .then block in passport.deserializeUser function
this will work:
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user)
});
});
I am working on a little project here and I ran into an issue after hooking up "register" and "login".
I did this through NodeJS with Express.
The error I am having is:
Access to XMLHttpRequest at 'api' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
That appears in the console whenever I try to fetch the products from the API. I do not get this error if I haven't logged in to an account, but if I have logged in to an account that happens.
Here is my Nodejs code:
const express = require("express");
const mysql = require("mysql");
const cors = require("cors");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const bcrypt = require("bcrypt");
const saltRounds = 10;
const app = express();
app.use(
cors({
origin: ["http://localhost:3000"],
methods: ["GET", "POST"],
credentials: true,
})
);
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
session({
key: "",
secret: "",
resave: false,
saveUninitialized: false,
cookie: {
expires: 60 * 60 * 24,
},
})
);
app.use(express.json());
const db = mysql.createConnection({
user: "",
host: "",
password: "",
database: "",
});
app.post("/register", (req, res) => {
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const username = req.body.username;
const phone = req.body.phone;
const password = req.body.password;
const email = req.body.email;
bcrypt.hash(password, saltRounds, (err, hash) => {
db.query(
"INSERT INTO `accounts`(`firstName`, `lastName`, `username`, `password`, `email`, `phone`) VALUES (?,?,?,?,?,?)",
[firstName, lastName, username, hash, email, phone],
(err, result) => {
console.log(err);
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("/login", (req, res) => {
const email = req.body.email;
const password = req.body.password;
let sql = `SELECT * FROM accounts WHERE email="${email}"`;
db.query(sql, (err, result) => {
try {
bcrypt.compare(password, result[0].password, (err, compResult) => {
if (err) throw err;
if (compResult) {
req.session.user = result;
res.send(compResult);
} else if (!compResult) {
res.send({ message: "Incorrect Password or Email!" });
}
});
} catch (err) {
res.send({ message: "Email does not exist!" });
}
});
});
Let me know if there is anything else you need!
I am new to sessions and this is my first serious coding project. I've tried a million things and I can't figure out why the session isn't persisting through different routes. When I log req.session.id from two routes, it gives me two different ids when it should be the same one.
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const session = require('express-session');
const bcrypt = require('bcrypt');
let User = require('./models/user.model');
const MongoStore = require('connect-mongo')(session);
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.set('trustproxy', true);
app.use(cors(corsOptions));
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully")
})
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
const SESS_NAME = 'session';
const SESS_SECRET = 'youshouldchangethis'
const IN_PROD = false;
app.use(session({
name: SESS_NAME,
resave: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
saveUninitialized: true,
secret: SESS_SECRET,
proxy: true,
cookie: {
sameSite: true,
secure: IN_PROD,
}
}));
The login route creates the session (the session is stored inside Mongodb just fine at this point), then react redirects to dashboard, where req.session comes back undefined and I'm unable to access that session. Here's the login and dashboard routes. Any help is greatly appreciated!
app.post('/login', (req, res) => {
console.log("in login post");
User.findOne({ email: req.body.email })
.then(user => {
bcrypt.compare(req.body.password, user.password, function (err, result) {
if(result == true){
req.session.userId = user._id;
console.log(req.session.id);
res.send(user);
} else {
res.send('Authentication Failed');
}
})
})
.catch(err => res.send('Authentication Failed'));
});
// Dashboard Router
app.get('/dashboard', (req, res) => {
if (req.session.userId){
User.findOne({ email: req.session.user.email }) // FIX: not able to find session / user
.then(user => {
console.log("found user")
// req.session.user = user;
res.send(user);
})
.catch(err => {
//req.session.reset();
res.send(err);
})
} else {
console.log(req.session.id);
}
});
I found this in express-session docs, maybe this is what you are looking for :
Session.save(callback)
....
There are some cases where it is useful to call this method, for example, redirects, long-lived requests or in WebSockets.
req.session.save(function(err) {
// session saved
})
Currently a user can sign in with github, and i can see it gets the req.user in the callback function, and on passport github file
console.log(`frontid ${req.user.id}`) // logs user id
and passport
console.log(`backbro ${id}`); // logs an id
however, when i go on this route, the github user returns null and im not sure why. There were a few times, i see the signed in github user return in the current_user route, however its rare that i see it now. It sometimes shows, sometimes dont. Kinda wierd. Could it be a session issue ?
router.get("/current_user", (req, res) => {
if(req.user){
res.status(200).send({ user: req.user});
} else {
res.json({ user:null})
}
});
yes i looked at the following links, still no suitable answer.
Node + Express + Passport: req.user Undefined
req.user undefined after twitter authentication using express sever, passport.js
The way im accessing this link, is by explictily calling
localhost:8000/api/users/auth/github
in the address bar.
routes/users
router.get('/auth/github', passport.authenticate('github', {
scope:[ 'profile', 'id']
}));
router.get('/auth/github/callback',
passport.authenticate('github', { session:true, failureRedirect: 'http:localhost:8001/signIn' }),
function(req, res) {
// Successful authentication, redirect home.
// var token = jwt.sign({ id: req.user.id}, process.env.JWT_SECRET );
// // res.cookie("jwt", token, { expires: new Date(Date.now() + 10*1000*60*60*24)});
// jwt.verify(token, process.env.JWT_SECRET, function(err, data){
// console.log(err, data);
// })
const user = req.user
req.logIn(user, err => {
models.User.findOne({
where: {
id: req.user.id,
},
}).then(user => {
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET);
// res.cookie("jwt", token, { expires: new Date(Date.now() + 10*1000*60*60*24)});
jwt.verify(token, process.env.JWT_SECRET, function(err, data){
console.log(err, data);
})
res.redirect('http://localhost:8001');
// console.log(req.user)
});
});
console.log(`frontid ${req.user.id}`)
// res.redirect('')
// console.log('this works', token);
});
passport-github.js
const GitHubStrategy = require('passport-github2').Strategy;
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const models = require("../models/");
// passport.serializeUser((user, done) => {
// // push to session
// done(null, user.id);
// console.log(user.id)
// });
// passport.deserializeUser((id, done) => {
// models.User.findOne({
// where: {
// id,
// },
// }).then(user => done(null, user))
// .catch(done);
// });
module.exports = async (passport) => {
passport.use(
new GitHubStrategy(
{
clientID: process.env.clientID,
clientSecret: process.env.secret,
callbackURL: 'http://127.0.0.1:8000/api/users/auth/github/callback',
passReqToCallback: true,
profileFields: ['id', 'login']
},
(req, accessToken, refreshToken, profile, done) => {
const { id, login, email} = profile._json;
console.log(`backbro ${id}`);
// console.log(req)
models.User.findOne({
where:{
id: id
}
}).then( user => {
// if user is found
if(user){
return done(null, user)
}
// else create new user
else{
models.User.create({
id: id,
username:login,
email: email,
createdAt: Date.now()
}).then( user => {
console.log('github user created');
return done(null, user);
})
}
})
}
)
);
passport.serializeUser((user, done) => {
// push to session
return done(null, user.id);
});
passport.deserializeUser((userId, done) => {
// console.log('calling deserial' + userId);
// // TODO: findByPk syntax? findById deprecated? Try later after sucessfully record data in DB
models.User
.findOne({ where: { id: userId } })
.then(function(user){
// console.log(user);
return done(null, userId);
}).catch(function(err){
done(err, null);
});
// return done(null, id);
});
}
app.js
const express = require('express');
const app = express();
const userRoute = require('./routes/users');
const postRoute = require('./routes/posts');
const bodyParser = require('body-parser');
const logger = require('morgan');
const session = require('express-session');
const cookieParser = require('cookie-parser') ;
const dotenv = require('dotenv');
const env = dotenv.config();
const cors = require('cors');
const models = require('./models/');
const host = '0.0.0.0';
const PORT = process.env.PORT || 8000;
const passport = require('passport');
const path = require('path');
const Sequelize = require('sequelize');
const SequelizeStore = require('connect-session-sequelize')(session.Store);
const proxy = require('express-http-proxy');
app.use(function(req, res, next) {
res.locals.user = req.user; // This is the important line
// req.session.user = user
console.log(res.locals.user);
next();
});
app.use(cors({
origin: process.env.ALLOW_ORIGIN,
credentials: false,
allowedHeaders: 'X-Requested-With, Content-Type, Authorization',
methods: 'GET, POST, PATCH, PUT, POST, DELETE, OPTIONS',
exposedHeaders: ['Content-Length', 'X-Foo', 'X-Bar'],
}))
var sequelize = new Sequelize(
process.env.POSTGRES_DB,
process.env.POSTGRES_USER,
process.env.POSTGRES_PASSWORD,{
"dialect": "sqlite",
"storage": "./session.sqlite"
});
myStore = new SequelizeStore({
db:sequelize,
})
if (!process.env.PORT) {
require('dotenv').config()
}
// console.log(process.env.DATABASE_URL);
if (!process.env.PORT) {
console.log('[api][port] 8000 set as default')
console.log('[api][header] Access-Control-Allow-Origin: * set as default')
} else {
console.log('[api][node] Loaded ENV vars from .env file')
console.log(`[api][port] ${process.env.PORT}`)
console.log(`[api][header] Access-Control-Allow-Origin: ${process.env.ALLOW_ORIGIN}`)
}
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'build')));
// We need a store in order to save sessions, instead of the sessions clearing out on us :)
require('./config/passport')(passport); // PASSPORT Init
require('./config/passport-github')(passport); // PASSPORT Init
app.use(cookieParser());
app.use(bodyParser.json());
app.use(session({
store: myStore,
saveUninitialized: false,
resave:false,
cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 }, // 30 days
secret : process.env.JWT_SECRET,
}));
myStore.sync();
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended:false}));
// this code may be useless or useful, still trying to understand cors.
app.use('/api/users', userRoute );
app.use('/api/posts', postRoute );
// In order to use REACT + EXPRESS we need the following code, alone with a build
// in the client folder we run a npm run build in the client folder then it is referred
// in the following code.
app.use(express.static(path.join(__dirname, 'client/build')));
if(process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client/build')));
//
app.get('*', (req, res) => {
res.sendfile(path.join(__dirname = 'client/build/index.html'));
})
}
//build mode
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname+'/client/public/index.html'));
})
models.sequelize.sync().then(function() {
app.listen(PORT, host, () => {
console.log('[api][listen] http://localhost:' + PORT)
})
})