see code below. its not storing a session in my database. I cant figure it. I have executiion file app.js. I have everythin setup and running but storing sessions in database dont work.. I posted the same question before but got no luck...
var express = require('express');
var mysql = require('mysql2');
var path = require('path');
var session = require('express-session');
var port = 3000;
var app = express();
var MySQLStore = require('mssql-session-store')(session);
app.use(session({
secret: 'tee tee',
resave: false,
saveUninitialized: false,
store: new MySQLStore(options)
}));
var connection = mysql.createConnection ({
host: 'localhost',
user: 'root',
password: '....',
database: 'node'
});
connection.connect(function(error) {
if(error) {
throw error;
} else {
console.log("We are now successfully connected with mySQL");
}
});
var options = {
connection: connection,
ttl: 3600,
reapInterval: 3600
};
app.get('/', (req, res) => {
res.sendFile('home.html', {
root: path.join(__dirname, './views')
});
});
app.listen(port, (req, res) => {
console.log('the server is running, ' + ' please, open your browser at http://localhost:%s', port);
});
It appears as you are using mssql-session-store (Microsoft SQL) to connect to MySQL.
Try using the npm package express-mysql-session:
https://www.npmjs.com/package/express-mysql-session
Like MySQL and MSSQL, there are many variants of SQL and SQL like databases so it is important you are precise with the database you are using.
Your line (below) should be the only issue. It is specifying the use of the Microsoft SQL session store package when you are trying to use the MySQL session store.
var MySQLStore = require('mssql-session-store')(session);
By changing it to
var MySQLStore = require('express-mysql-session')(session);
You specify the use of the mysql session store (Make sure you download the NPM package above first)
Related
While prepping an application for deployment, an error:
Error: Dialect needs to be explicitly supplied as of v4.0.0
started popping up whenever i run npm run develop. i'm using a .env file for my environmental variables. The connection.js code is :
const Sequelize = require('sequelize');
require('dotenv').config({path: '../.env'});
let sequelize;
if (process.env.JAWSDB_URL) {
sequelize = new Sequelize(process.env.JAWSDB_URL);
} else {
sequelize = new Sequelize(
process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD,
{
dialect: 'mysql',
host: 'localhost',
port: 3306
}
);
}
module.exports = sequelize;
The server.js file is:
const path = require('path');
const express = require("express");
const cors = require("cors");
const routes = require("./routes");
const sequelize = require("./config/connection");
const app = express();
const PORT = process.env.PORT || 8080;
var corsOptions = {
//for online use
// origin: "https://operations-limit-database.herokuapp.com"
//first trying this without credentials to see how it works
// credentials: true,
//for local use
origin: "http://localhost:3000"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// turn on routes
app.use(routes);
// simple route
//the below two are for deployed builds
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'));
});
//this is for local build only
// app.get("/", (req, res) => {
// res.json({ message: "Welcome to Homeschool's Op Limit Database" });
// });
// turn on connection to db and server
//{ force: false } to drop tables and recreate
sequelize.sync().then(() => {
app.listen(PORT, () => console.log(`Server is running on port ${PORT}.`));
});
And the .env file looks like below:
DB_NAME= 'xxxx'
DB_USER= 'yyyy'
DB_PASSWORD= 'zzzz'
DB_SECRET='aaaa'
Not sure what I.m missing, it was up and running over the weekend and then just stopped. Anything i can try would be appreciated.
So far i've tried reordering the .env, changing databases, and rebuilding the app, all to no avail.
This happens when you dont pass dialect to sequelize properly, make sure that you are passing the string and the environment variables are getting passed, usually it is the case.
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'mysql',
dialectOptions: {
// Your mysql2 options here
}
})
Documentation
I am very new to programming so I do apologize if this is a really simple question.
So, I have been trying to connect my React Native application to the MySQL Database using Node and Express server, but I keep on getting the following error (I have checked other stackoverflow questions as well, but nothing has helped):
Error
I have checked my host name and port number multiple times and the all the information seems to be correct. I am not sure what is wrong with the following code:
var express = require("express");
var app = express();
var mysql = require("mysql");
var bodyParser = require("body-parser");
const { application } = require("express");
app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.urlencoded({ extended: true }));
var connection = mysql.createConnection({
host: '127.0.0.1', // Your connection adress (localhost).
port: "3306",
user: "root", // Your database's username.
password: "", // Your database's password.
database: "birthdays", // Your database's name.
});
connection.connect(function (error) {
if (error) console.log(error);
else console.log("connected");
});
// Starting our server.
app.listen(4547, () => {
console.log("Go to http://localhost:4547/dinners so you can see the data.");
});
app.get("/users", function (req, res) {
con.query("select * from users", function (error, rows, fields) {
if (error) console.log(error);
else {
console.log(rows);
res.send(rows);
}
});
});
I run this code by typing "node fileName.js" in the terminal.
I don't know if this is helpful, but I have also connected by MySQL database to MySQL Workbench.
Any help is appreciated!
I am currently working on the API of a React.js project. I have no trouble running SQL requests with databases on MySql servers using Express as long as the SQL request only implies a single database.
My problem: I now have to run an SQL request which implies using data from several databases and I do not know how to do it.
What I currently do in my server.js file to run SQL on a single database:
...
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mysql = require('mysql');
...
let sql = "";
...
// *************************
// CLIENT & DB CONFIGURATION
// *************************
const app = express();
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
var server = app.listen(3001, "127.0.0.1", function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});
app.use(cors());
const connection = mysql.createConnection({
host : 'myhost.fr',
user : 'someone',
password : 'aZefdt%',
database : 'SuiviTruc',
multipleStatements : true
});
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected with SuiviTruc database...')
});
// **************
// Request sample
// **************
app.get('/SelectAffaire_',(req, res) => {
let sql=`SELECT * FROM t_Affaire_;`
connection.query(sql, (error, result)=> {
if (error) throw error;
res.send(result);
})
})
Thanks for your help!
I need display data in table from MySql database, but I dont know how it do this.
I tried found something example or example application with source code, but I nothing found.
Maybe someone help me with this?
I tried with node.js express:
var mysql = require('mysql');
var https = require('https');
var con = mysql.createConnection({
host: "https://adress to database",
user: "user",
password: "password",
database: "db"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
But i get error:
Error: getaddrinfo ENOTFOUND
here is a simple way to get data from mySQL and export it as json:
var http = require('http');
var mysql = require('mysql');
var bodyParser = require("body-parser");
var express = require('express');
var app = express();
var pool = mysql.createPool({
host: 'db location',
user: 'username od db',
password: 'something',
database: 'yourdatabase',
port:3306
});
// define rute
var apiRoutes = express.Router();
var port = 9000;
apiRoutes.get('/', function (req, res) {
res.json({ message: 'API works' });
});
apiRoutes.get('/data', function (req, res, next) {
pool.getConnection(function (err, connection) {
if (err) {
console.error("error hapened: " + err);
}
var query = "SELECT * FROM imena ORDER BY id ASC";
var table = ["imena"];
query = mysql.format(query, table);
connection.query(query, function (err, rows) {
connection.release();
if (err) {
return next(err);
} else {
res.json({
success: true,
list_users: rows
});
}
});
});
});
app.use('/api', apiRoutes);
// starting
app.listen(port);
console.log('API radi # port:' + ' ' + port);
But i still suggest that you start using noSQL databases like firebase because of they are simple and faster.
In order to show data from MySQL Database, you need to provide application interface(s) to Angular environment and only then Angular can use the data. There are few techniques in which you can design interfaces, REST is the most popular though.
First you need to understand that Angular is Front-End framework and it can only send requests to backend such as Node js, PHP etc.Thus, first you need to chose your backend. Node is popular with express js module, but if you still don't have mySQL set, go for firebase real time database. If you decide node js => express => mySQL check tutorial online.
new to nodejs. this might be a silly/easy question
I have an Express App and i am using mysql for persistent sessions. (using express-mysql-session to do that).
Here's code snippet from app.js:
var express = require('express');
var session = require('express-session');
var SessionStore = require('express-mysql-session');
var app = express();
app.use(session({
store: new SessionStore({
host: 'localhost',
user: 'test',
password: 'test',
database: 'test'
}),
secret: 'secret_key',
resave: false,
saveUninitialized: false
}));
routes.js
module.exports = function(app) {
app.post('/login', wrap(function* (req, res) {
var email = req.body.email;
var password = req.body.password;
var response = yield new AccountController().login(email, password);
if (response.status === 'success') {
req.session.account = {
accountId: response.accountId,
accountStatus: response.accountStatus
};
req.session.save(function(err) {
if (err) console.log('error in saving session: ' + err);
});
}
}
}));
The get and set method of express-mysql-session are called everytime a request is sent.
I wanted to know how can i set my custom data into the persistent session store without using any other library like passport.
and also how to read the store too.