I've been trying to use express-session on two local servers.
The first server is for manipulating the database and the second is for loading pages.
I want to save some data in the session from the first server and use it in the second server.
Here's the code of the first API
require("dotenv").config();
const express = require('express');
const mysql = require("mysql");
const crypto = require("crypto");
const cors = require("cors");
const apiApp = express();
apiApp.use(express.json());
apiApp.use(cors());
const pool = mysql.createPool({
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: "localhost"
});
var algorithm = 'aes256'; // algorithm
var key = 'password';
apiApp.post('/api/Connexion', (req, res) => {
let cipheriv = crypto.createCipher(algorithm, key);
let encryptedPassword = cipheriv.update(req.body.motDePasse, 'utf8', 'hex') + cipheriv.final('hex');
var data = [req.body.courriel, encryptedPassword];
const query = "SELECT * FROM utilisateurs WHERE courriel=? AND motDePasse=?";
pool.query(query, data, (error, results) => {
if (results[0] && !error) {
res.send(true);
req.session.courriel = req.body.courriel;
} else {
res.send(false);
}
});
});
module.exports = apiApp;
And the second
require("dotenv").config();
const express = require('express');
const cors = require("cors");
const path = require("path");
const coreApp = express();
coreApp.use(express.json());
coreApp.use(cors());
let dir = path.resolve(__dirname, '..', '..') + '/'
coreApp.use(express.static(dir));
coreApp.get('/connexion', (req, res) => {
if (req.session != undefined) {
console.log(req.session.courriel);
}
res.sendFile(dir + "index.html");
});
coreApp.get('/application', (req, res) => {
res.sendFile(dir + "application.html");
});
coreApp.get('/:a', (req, res) => {
res.redirect("/");
});
module.exports = coreApp;
So, I am trying to set the session variable at line 64 of the first code and use it at line 17 of the second code.
How can I do it ?
Thanks !
You can share session data between servers if you use a shared database as the session store for express-session, often redis, but any database can work as long as both servers access the same database for express-session storage and express-session is configured properly.
There are express-session storage providers for dozens of databases, including express-mysql-session that works with the database that you're already using.
Related
I use the mvc routing in my node app and Whenever I post a request to the cpanel server side (route file) for processing in my node app I receive a 404 error but the route are accurate when I checked. but it works well on localhost andon cpanel when i try not to use mvc routing i.e post and receive the request in app.js.
Frontend Code:
$.ajax({
url: "/rest",
method: "post",
contentType: "application/json",
data: JSON.stringify({
email: 'akpulufabian#gmail.com', password: '0000'
}),
success: (data) => {
console.log(data)
}
});
Backend Code [route file]
const express = require("express");
const bodyParser = require('body-parser');
const parser = bodyParser.json({ limit: '16mb'});
const { rest, index } = require('../controllers/rest');
const router = express.Router();
router.get('/index', index);
router.post('/rest', parser, rest);
module.exports = router ;
Backend Code [controller file]
const express = require("express");
const bcrypt = require('bcryptjs');
require('dotenv').config();
const nodemailer = require("nodemailer");
const jwt = require('jsonwebtoken');
const path = require("path");
const fs = require('fs');
const mongodb = require('mongodb');
const { ObjectId, MongoDBNamespace } = require('mongodb');
//const {dbConn} = require('../db');
let db;
const app = express();
const maxAge = 3 * 24 * 60 * 60;
const createToken = (id) => {
return jwt.sign({ id }, 'news app secret', {
expiresIn: maxAge
});
};
const index = (req, res) => {
res.render('rest')
}
const rest = (req, res) => {
res.status(200).send({ user: "test successfully carried out..." })
}
module.exports = {
index,
rest
};
I am new at Node.js and trying to make an API that will do CRUD operations in sql server. The problem for me is that I can get the data but cannot post it, and get the error "cant get /". I know there are similar questions about this subject but nothing works for me so I thought maybe my code has different kinds of error. Any help will be appreciated and save my life in a way. Also, this is my first question on stackoverflow, sorry for the possible mistakes..
Here is the server.js
const sql = require('mssql');
const express = require('express');
const bodyParser = require('body-parser');
var port = process.env.port || 5000;
const sqlConfig = require('./connection/connect')
const app = express();
app.use(express.json()); // json desteklemesi için
app.use(express.urlencoded({ extended: true }));
app.get("/test", (req, res, next) => {
new sql.ConnectionPool(sqlConfig).connect()
.then(pool => {
return pool.query('select * from tblProfile')
})
.then(result => {
res.send(result);
})
})
app.post('/test', (req, res) => {
let name = req.query.name;
let lastname = req.query.lastname;
let email = req.query.email;
let password = req.query.password;
let sql = "INSERT INTO tblProfile(name,lastname,email,password) VALUES(? ? ? ?)";
conn.query(sql, [name, lastname, email, password], (err, result) => {
if (err) throw err;
res.write("inserted.");
res.end();
});
app.listen(port, () => {
console.log("working: " + port)
})
});
This is the connect.js
var sqlConfig = {
server: '192.168.1.2',
database: 'profile',
user: 'username',
password: 'user',
};
module.exports = sqlConfig;
This is happening because you aren't responding or sending anything to that route
So if you want to get rid of the error
Run
app.get('/', (req,res)=>{
res.send('hello world')
}
But if you want to send a static file to the route
Create a folder call public * note it can be anything
And type
var path = require('path');
app.use(express.static(path.join(__dirname, 'public')));
Then you can access code in the dir
And as for the writing I think you should try this
app.post('/test', (req, res) => {
let name = req.body.name;
let lastname = req.body.lastname;
let email = req.body.email;
let password = req.body.password;
let sql = "INSERT INTO tblProfile(name,lastname,email,password VAUES(? ? ? ?)";
conn.query(sql, [name, lastname, email, password], (err, result) => {
if (err) throw err;
res.write("inserted.");
res.end();
});
Change query to body
Since you installed body-parser
Taking a quick look over your code, the only issues I can see are in your query to submit the data. Within your query statement, I added a closed parentheses after the variables to be entered into the database and made a typo correction to the word Values. I also changed up how the data is retrieved from req.query to destructure it and simply the code a bit. Based on everything else I saw, and the fact that you are able to get data from the database, this should work out fine. If it doesn't, I would recommend inserting some console.log() statements in the post query to see where it might be having issues and why. For example, you could run console.dir(req.query); in your post route to see what data is actually coming from the req and make sure it is all there. If something is missing, then the query won't actually execute. If this doesn't work, let me know, along with the information from any console logs you did and I'll take another look at it.
const sql = require('mssql');
const express = require('express');
const bodyParser = require('body-parser');
var port = process.env.port || 5000;
const sqlConfig = require('./connection/connect')
const app = express();
app.use(express.json()); // json desteklemesi için
app.use(express.urlencoded({ extended: true }));
app.get("/test", (req, res, next) => {
new sql.ConnectionPool(sqlConfig).connect()
.then(pool => {
return pool.query('select * from tblProfile')
})
.then(result => {
res.send(result);
})
})
app.post('/test', (req, res) => {
//console.dir(req.query);
let {name, lastname, email, password} = req.query;
let sql = "INSERT INTO tblProfile(name,lastname,email,password) VALUES(? ? ? ?)";
conn.query(sql, [name, lastname, email, password], (err, result) => {
if (err) throw err;
res.write("inserted.");
res.end();
});
app.listen(port, () => {
console.log("working: " + port)
})
});
I get: Error: Error: ER_BAD_DB_ERROR: Unknown database, when trying to connect via a connection pool to my AWS MySql database.
I've triple checked the database credentials, so this must be either syntactical or methodical.
database is a MySql RDS on amazon web services and I'm using the express middleware on node js.
server.js
const express = require('express');
const next = require('next');
const port = process.env.PORT || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const cors = require('cors');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const pool = require('../lib/db');
app.prepare().then(() => {
const server = express()
server.use(cors());
server.get('/', (req, res, next) => {
let sql = 'SELECT * FROM products'
pool.query(sql, (err, result, fields) => {
if (err) {
throw new Error(err);
}
return result.json({
data: rows
})
}
)
})
...
db.js
const mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit: 10,
host: 'XXX',
user: 'XXX',
password:'XXX',
database: 'XXX'
})
pool.getConnection((err, connection) => {
if (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection was closed.')
}
if (err.code === 'ER_CON_COUNT_ERROR') {
console.error('Database has too many connections.')
}
if (err.code === 'ECONNREFUSED') {
console.error('Database connection was refused.')
}
} if (connection) connection.release()
return
})
module.exports = pool
I am not that familiar with Node.js so don't really say if the code or syntax is correct, but i get what you're trying to accomplish.
A middle ware which connects applications to a db, using a pool of connection.
https://github.com/mysqljs/mysql
This project might help you more than i can.
Its related to the same concept.
So, being relatively new to Node.js and MySql, I wasn't as confident in my syntax as I should have been. It was a methodical issue.
When creating a connection pool, you have to have the name of the database. For some reason, AWS will give you a "database instance" and put "-" for the DBName. Thus I assumed they were of the same value.
I used MySQL Workbench to extract the Database Name, which is entirely different to the DB Instance I entered on Amazon.1
I'm trying to use two Node.js express servers on a Windows Server 2012, each one with a different FQDN (example1.b.br | exemple2.b.br).
The applications are two Watson Chatbots, so both of them need to use route /conversation to communicate with IBM.
One chatbot uses port 443 and the other one use 8443.
The problem is: Each one of them are in different directories and have their own subdirectory called 'public', but when I execute both servers, the one using port 8443 uses the port 443 server's 'public' subdirectory.
Chatbots
certificates
Chatbot1
node_modules
public
css
script
Chatbot2
node_modules
public
css
script
Chatbot1 app.js:
const AssistantV1 = require('watson-developer-cloud/assistant/v1');
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
const https = require('https');
var fs = require('fs');
var httpApp = express();
var workspace;
var options = {
key: fs.readFileSync('certificates/key.pem'),
cert: fs.readFileSync('certificates/server.crt')
};
const app = express();
app.use(bodyParser.json());
app.use(express.static('./public'));
const port = 80;
const httpsPort = 8443;
httpApp.set('port', process.env.PORT || 80);
const assistant = new AssistantV1({
username: 'XXXXX',
password: 'XXXXX',
url: 'https://gateway.watsonplatform.net/assistant/api/',
version: '2018-02-16'
});
workspace = 'XXXXXXX';
app.post('/conversation/', (req, res) => {
const { text, context = {} } = req.body;
const params = {
input: { text },
workspace_id: workspace,
context,
};
assistant.message(params, (err, response) => {
if (err) res.status(500).json(err);
res.json(response);
});
});
try{
//var httpServer = http.createServer(httpApp, app).listen(port);
var httpsServer = https.createServer(options, app).listen(httpsPort);
//httpServer.listen(port, () => console.log(`Running on port ${port}`));
httpsServer.listen(httpsPort, 'exemple1.b.br', () => console.log(`HTTPS Running on port ${httpsPort}`));
console.log(`---------------------------------`);
console.log(`-----------ROBO INICIADO---------`);
console.log(`---------------------------------`);
}catch(err){
console.log(`*********************************`);
console.log(`*****Falha ao iniciar o Robo*****`);
console.log(`*********************************`);
console.log(err);
} */
Chatbot2 app.js:
const AssistantV1 = require('watson-developer-cloud/assistant/v1');
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
const https = require('https');
var fs = require('fs');
var httpApp = express();
var workspace;
var options = {
key: fs.readFileSync('certificates/key.pem'),
cert: fs.readFileSync('certificates/server.crt')
};
const app = express();
app.use(bodyParser.json());
app.use(express.static('./public'));
const port = 80;
const httpsPort = 443;
httpApp.set('port', process.env.PORT || 80);
const assistant = new AssistantV1({
username: 'xxxxxxx',
password: 'xxxxxx',
url: 'https://gateway.watsonplatform.net/assistant/api/',
version: '2018-02-16'
});
workspace = 'XXXXXXX'
app.post('/conversation/', (req, res) => {
const { text, context = {} } = req.body;
const params = {
input: { text },
workspace_id: workspace,
context,
};
assistant.message(params, (err, response) => {
if (err) res.status(500).json(err);
res.json(response);
});
});
try{
var httpsServer = https.createServer(options, app).listen(httpsPort);
httpsServer.listen(httpsPort, 'exemple2.b.br', () => console.log(`HTTPS Running on port ${httpsPort}`));
console.log(`---------------------------------`);
console.log(`-----------ROBO INICIADO---------`);
console.log(`---------------------------------`);
}catch(err){
console.log(`*********************************`);
console.log(`*****Falha ao iniciar o Robo*****`);
console.log(`*********************************`);
}
How can I "force" the server to use its own subdirectory?
"Problem" solved.
Actually, it was my lack of study about how FQDN actually works and a little to blame on Anti-virus.
example2.b.br don't need the ":443" on its url, because the port is default for HTTPS.
But when I use example1.b.br, it needs ":8443" after (https://example1.b.br:8443).
At least this simple mistake make me learn about this detail.
After that, I discovered that the server anti-virus were blocking some files. After creating an exception on the port to communicate only through intranet, the problem got solved.
i made a very simple api using express.js. Here's the code:
var express = require('express');
var app = express();
var morgan = require('morgan');
var UserModel = require('../Models/User')
app.use(morgan('short'));
app.use(express.json());
app.get('/getAll', (req, res) => {
res.status(200).json({auth: true});
})
app.post('/addUser', (req, res) => {
const { name, email, password } = req.body;
UserModel.create({name, email, password}, (err, user) => {
if(err) return res.status(500).end({auth: false})
res.status(200).end({user});
});
});
module.exports = app;
And here's the userModel:
const mongoose = require("mongoose")
const Schema = mongoose.Schema;
const UserSchema = new Schema(
{
name: String,
email: String,
password: String,
},
{timestamps: false}
);
mongoose.model("User", UserSchema);
module.exports = mongoose.model("User");
This is the main server.js file:
var express = require('express');
var app = express();
const AuthController = require("./Controllers/AuthController");
const PORT = 3001;
app.use("/api/auth", AuthController);
app.listen(PORT, () => console.log(`Listening on port ${PORT}..`))
This is the db.js file:
const mongoose = require('mongoose');
const dbRoute = "mongodb://<user>:<password>#<stuff>/nodejs-db";
mongoose.connect(
dbRoute,
{useNewUrlParser: true}
);
So here's the problem. when i try to make a request to this api using Insomnia, the requests doesn't end. Basically Insomia starts sending the request and i have to wait like 20 secs until i get something on my express terminal. If i end the request manually i get this:
::ffff:127.0.0.1 - POST /api/auth/addUser HTTP/1.1 - - - - ms
I tried looking online but couldn't find anything useful.
I come from a django backgrond. I'm new to Node and Express js.
Edit:
The problem is only with the posts requests because whenever i make a get request it returns immediately {auth: true}.
Change your .end() to .send()
app.post('/addUser', (req, res) => {
const { name, email, password } = req.body;
UserModel.create({name, email, password}, (err, user) => {
if(err) return res.status(500).send({auth: false})
res.status(200).send({user});
});
});
I solved this problem.
Apparently the problem was that my db connection was on another file.
All i did was to move the content from the db.js file to my server.js file.
I forgot to include my db file.