Can't get and read GET request - mysql

I have a problem using Node.js. I am sending data via GET request to special script, which should read this data and write it in MySQL. Here is an example of GET request (very long):
http://demo.com/?&bssid=16~6D~57~7F~D8~AD&mac=60~01~94~2B~A8~85&rssi=0&hotspots_list=~~0_74~85~2A~39~77~48_-85~~~~1_78~8C~54~33~D8~3C_-91~~~
~2_64~6E~EA~0E~B3~26_-84~~~~3_76~85~2A~39~77~49_-87~~~~4_2C~33~7A~16~91~3B_-92~~~~5_54~BE~F7~6B~EE~43_-92~~~~6_98~DE~D0~AB~B8~64_-91~~~~7_14~DD~A9~1E
~F6~F8_-93~~~~8_64~6E~EA~0C~9A~3E_-84~~~~9_E8~DE~27~50~2A~12_-88~~~~10_84~C9~B2~0B~BA~C2_-81~~~~11_00~0F~94~BE~FC~44_-87~~~~12_56~BE~F7~6B~EE~44_-86~
~~~13_00~0E~8F~85~5F~73_-53~~~~14_0C~54~A5~A6~C1~1F_-87~~~~15_16~6D~57~7F~D8~AD_-78~~~~16_0E~54~A5~A6~C1~10_-92~~~~0_EC~1A~59~17~CF~5F_-91~~~~1_74~85
~2A~39~77~48_-92~~~~2_16~6D~57~7F~D8~AD_-77~~~~3_0C~54~A5~A6~C1~1F_-92~~~~4_0E~54~A5~A6~C1~10_-83~~~~5_84~C9~B2~0B~BA~C2_-82~~~~6_14~DD~A9~1E~F6~F8_-
92~~~~7_64~6E~EA~0C~9A~3E_-85~~~~8_E8~DE~27~50~2A~12_-93~~~~9_00~22~6B~56~2B~83_-92~~~~10_00~0E~8F~85~5F~73_-58~~~~11_00~0F~94~DB~DE~64_-91~~~~12_16~
DD~A9~1E~F6~F9_-92~~
I've done few experiments, and I found out, that it works fine in PHP, my code (only for output):
<?php
echo $_GET["bssid"]." ".$_GET["mac"]." ".$_GET["rssi"]." ".$_GET["hotspots_list"];
?>
But not in Node.js !This is my Node.js code:
var express = require("express");
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'host',
user : 'user',
password : 'pswd',
database : 'db'
});
var bssid, mac, rssi, hotspots_list;
const port = 3000;
const host = "0.0.0.0";
app.get('/', function (request, response) {
//Writing data to vars
bssid = request.query.bssid;
mac = request.query.mac;
rssi = request.query.rssi;
hotspots_list = request.query.hotspots_list;
//Sending request to MySQL server
connection.query(`INSERT INTO locations (mac, bssid_current, rssi_currnet, hotspots_list) VALUES ('${mac}','${bssid}','${rssi}','${hotspots_list}')`);
//Debugging line
console.log(`BSSID: ${bssid}`);
//Response
response.statusCode = 200;
response.setHeader('Content-Type', 'text/plain');
return response.send('Done');
});
app.listen(port, host, () => {
console.log(`Server running!`);
});

In your code, your route is /. And you are trying to access it via /server.js
Two solutions, either you add
app.get('/server.js', [...]) or you access it after removing server.js from your url.

Related

React Native Access mysql db using express

I need to access my Data from my mysql Database using express, on my server the data is as a json, but when i try to access it i always get 'undefined' and my express server crash
the json i have on the server :
[{"idProjet":1,"nomProjet":"test","dateDebut":"2021-05-18T22:00:00.000Z","nomAuteur":"mathieu","prenomAuteur":"jean","organisme":"idmc"}]
fetching code :
let id = 'id :';
const [data, setData] = useState([]);
useEffect(() => {
fetch('http://localhost:3000/projets')
.then(response => {return response.json()})
.then((json => {console.log(json);setData(json);}))
.catch(error => console.error(error));
console.log(data);
}, []);
Route.js code :
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database : 'agora'
});
// Starting our app.
const app = express();
// Creating a GET route that returns data from the 'users' table.
app.get('/projets', function (req, res) {
// Connecting to the database.
connection.getConnection(function (err, connection) {
// Executing the MySQL query (select all data from the 'users' table).
connection.query('SELECT * FROM projet', function (error, results, fields) {
// If some error occurs, we throw an error.
if (error) throw error;
// Getting the 'response' from the database and sending it to our route. This is were the data is.
res.send(results)
});
});
});
// Starting our server.
app.listen(3000, () => {
console.log('Go to http://localhost:3000/projets so you can see the data.');
});
The most common problem for this type of behavior is that you are using react-native on an android emulator. Android Emulator is using an IP-address different from localhost on windows machine. For more information, check here the official documentation.
So you can forward your port on the same port used by the android emulator (10.0.2.2) or you can change the port to 80 so you won't have any problem
You can go check this answer here

React.js + Express: how to run SQL requests implying several databases?

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!

How to store my session MySQL with express-mysql-session

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)

establishing a connection to database using environment variables

I'm creating an API for my app that fetches some data from my amazon db.
I have added environment variables to a custom.sh file in profile.d on my server. The weird thing is, I can print out those variables from my api, but the only variable that works when creating the connection is the user variable.
When I hard code the database credentials in the connection string it works just fine.
here is my custom.sh where I declare the environment variables
#custom environment variables, with the actual values removed
export DB_HOST=value1;
export DB_PASS=value2;
export DB_USER=value3;
export DB_NAME=value4;
here is my nodejs expressjs api file
var express = require('express');
var app = express();
var mysql = require('mysql');
var DB_HOST = formatEnvironmentVariable(process.env.DB_HOST);
var DB_USER = formatEnvironmentVariable(process.env.DB_USER);
var DB_PASS = formatEnvironmentVariable(process.env.DB_PASS);
var DB_NAME = "'"+process.env.DB_NAME+"'";
function formatEnvironmentVariable(env) {
env = "'"+env+"'";
return env
}
var pool = mysql.createPool({
host : DB_HOST,
user : DB_USER,
password : DB_PASS,
database : DB_NAME,
connectionLimit: 100,
debug: false
})
function QueryTheDatabase(req, res, querystring) {
pool.getConnection(function(err,connection){
if (err) {
connection.release();
res.json({"code" : 100, "status" : "Error in connection database"});
return;
}
console.log('connected as id ' + connection.threadId);
connection.query(querystring,function(err,rows){
connection.release();
console.log("error? "+err);
if(!err) {
res.json(rows);
}
});
connection.on('error', function(err) {
console.log("error");
res.json({"code" : 100, "status" : "Error in connection database"});
return;
});
});
}
app.get('theurl', function(req, res) {
QueryTheDatabase(req, res, "the query that works fine");
});
var server = app.listen(3000, function () {
var host = server.address().address;
var host = server.address().port;
});
I'm not exactly sure why only the DB_USER variable is set properly (it may be that some other process is sending that information). If you're running your shell script as such:
$ ./custom.sh
It won't work. It's essentially creating a sub-shell and the exported variables are local to that shell (they won't affect the parent)
The only way to make environment variables accessible to your node process would be to source the file first.
$ source ./custom.sh
I got it to work finally, turns out I didnt need to add ' ' with my format function.
instead of
var DB_HOST = formatEnvironmentVariable(process.env.DB_HOST);
var DB_USER = formatEnvironmentVariable(process.env.DB_USER);
var DB_PASS = formatEnvironmentVariable(process.env.DB_PASS);
var DB_NAME = "'"+process.env.DB_NAME+"'";
I wrote
var DB_HOST = process.env.DB_HOST;
var DB_USER = process.env.DB_USER;
var DB_PASS = process.env.DB_PASS;
var DB_NAME = process.env.DB_NAME;
For this I'll suggest To use
config npm
https://www.npmjs.com/package/config

NodeJS sessions, cookies and mysql

I'm trying to build an auth system and I have app.js
var express = require('express')
, MemoryStore = require('express').session.MemoryStore
, app = express();
app.use(express.cookieParser());
app.use(express.session({ secret: 'keyboard cat', store: new MemoryStore({ reapInterval: 60000 * 10 })}));
app.use(app.router);
and the route.index as
var express = require('express')
, mysql = require('mysql')
, crypto = require('crypto')
, app = module.exports = express();
app.get('/*',function(req,res){
var url = req.url.split('/');
if (url[1] == 'favicon.ico')
return;
if (!req.session.user) {
if (url.length == 4 && url[1] == 'login') {
var connection = mysql.createConnection({
host : 'localhost',
user : 'user',
password : 'pass',
});
var result = null;
connection.connect();
connection.query('use database');
var word = url[3];
var password = crypto.createHash('md5').update(word).digest("hex");
connection.query('SELECT id,level FROM users WHERE email = "'+url[2]+'" AND password = "'+password+'"', function(err, rows, fields) {
if (err) throw err;
for (i in rows) {
result = rows[i].level;
}
req.session.user = result;
});
connection.end();
}
}
console.log(req.session.user)
when I access http://mydomain.com/login/user/pass a first time it shows in the last console call but a second time access the cookie is clean
Why do you not just use Express's session handling? if you use the express command line tool as express --sessions it will create the project template with session support. From there you can copy the session lines into your current project. There more information in How do sessions work in Express.js with Node.js? (which this looks like it may be a duplicate of)
As for sanitizing your SQL, you seem to be using the library, which will santitize your inputs for your if you use parameterized queries (ie, ? placeholders).
Final thing, you are using Express wrong (no offence). Express's router will let you split alot of your routes (along with allowing you to configure the favicon. See Unable to Change Favicon with Express.js (second answer).
Using the '/*' route will just catch all GET requests, which greatly limits what the router can do for you.
(continued from comments; putting it here for code blocks)
Now that you have an app with session support, try these two routes:
app.get('/makesession', function (req, res) {
req.session.message = 'Hello world';
res.end('Created session with message : Hello world');
});
app.get('/getsession', function (req, res) {
if (typeof req.session.message == 'undefined') {
res.end('No session');
} else {
res.end('Session message: '+req.session.message);
}
});
If you navigate in your browser to /makesession, it will set a session message and notify you that it did. Now if you navigate to /getsession, it will send you back the session message if it exists, or else it will tell you that the session does not exist.
You need to save your cookie value in the response object:
res.cookie('session', 'user', result);
http://expressjs.com/api.html#res.cookie