Unable to fetch data from workbench Mysql using node js - mysql

// import express js
const express = require('express')
// import a body-parser
const bodyparser = require('body-parser');
// executing the express js
const app = express();
// import mysql packages
const mysql = require('mysql');
// use bodyparser in express
app.use(bodyparser.json);
// create an connection details for mysql database
var mysqlConnection = mysql.createConnection(
{
host:'localhost',
user:'root',
password:'keerthi#abitech',
database:'employeedb'
}
)
// To connect with mysql database
mysqlConnection.connect((err)=>{
if(!err)
console.log('DB is connected')
else
console.log('DB connection is failed \n Error: ' + JSON.stringify(err, undefined, 2));
});
// establish an data fetch from database
app.get('/employees', (res, req)=>{
mysqlConnection.query('SELECT * FROM employee', (err, results)=>{
if(err) throw err;
console.log(results);
res.send("post is send")
})
});
// creating an server
app.listen(3000, ()=>console.log("server is running in port number 3000"));
This is my code. I am not able to fetch an data from mysql workbench.
The page is loading only does not give any response.
If i pass the link in postman it shows like this
Could Not Get Any Response

You are currently not sending your data back to the endpoint. Assuming that your connection is successful, you should res.send(results) instead of res.send("post is send") in order to send your results to the /employees endpoint.
Hope this fixes your problem.

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 resolve 502 Mysql query error on Netlify (Express server)

I have a React app + Express server deployed on netlify here. I have a simple api endpoint that queries my MySql DB on AWS.
When I make the api request I am given a "Failed to load resource: the server responded with a status of 502".
If I just return a simple
res.send("simple response")
then everything works fine and I get the response on the client. Could someone point me in the right direction on what I should be looking for?
I've tried to disable the skip_name_resolve parameter on my db to see if the hostname mattered, opening up access to all ports / ip's on the aws security group, look up common examples of express + mysql server implementations, lookup the netlify function docs, and using async await in the server.
// client.jsx
useEffect( () => {
fetch("/.netlify/functions/server/api/getSalesData")
.then(res => res.json())
.then(res => console.log(res));
// server.js
const express = require("express");
const bodyParser = require("body-parser");
const serverless = require('serverless-http');
const mysql = require("mysql");
const db = mysql.createConnection({ ... });
db.connect(function(err) {
if (err) throw err;
console.log('You are now connected...')
});
const app = express();
const router = express.Router();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.get("/api/getSalesData", (req, res) => {
// res.send({ express: "Hello from express" });
db.query("SELECT * FROM Sales LIMIT 5", (err, rows) => {
if (err) throw err;
res.send(rows);
});
});
app.use('/.netlify/functions/server', router);
module.exports = app;
module.exports.handler = serverless(app);

Angular 4 with nodejs and Mysql connectivity

I am new in angular and node js. I want to know how angular connect with node js with mysql server. Which simple return query result. Can anyone help me.
Angular is a fronend framework and nodejs can be used to implement a backend for a system. And you can use mysql as your DBMS.
You have to implement your backend and frontend separately. From backend you are exposing endpoints, routes, apis to the external applications.
And you can access those apis,routes from angular using HttpClient module. You can make Http requests using that.
Hope this helps
You may need to use some libraries to make a connection between angular frontend and backend with MySQL database.
You will need the express.js to handle the backend for the data request. Because you use the MySQL database, the database language would be different from any others such as MongoDB. The express provided database integration for the different databases.
You also need a body-parser as a middleware to parse the request body. This is a very important part of your project. The req is very complicated and this middleware can help to get the information which you need.
Here is a sample of how to use express connect mysql.
var express = require('express');
var query = require('./query')
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var app = express();
//Middleware for bodyparsing using both json and urlencoding
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
//login
app.post('/login',(req,res)=>{
var opts = req.body;
query(" SELECT *FROM `v_users` WHERE userAcount = ?",opts.userName).then((result)=>{
var response = result[0];
if(opts.password !== response.u_password){
return res.send({
errorCode:'404',
errorMsg:'password error'
})
}
//loginToken
var loginToken = response.userAcount + Math.random()*Math.pow(10,16)
res.send({
loginToken:loginToken
})
})
})
var server = app.listen(3000,()=>{
console.log('success')
})
Here is the query method:
(function() {
var mysql = require('mysql');
// var session = require('cookie-session');
var query = (sql,key) => {
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root123',
database: 'm_users'
});
connection.connect()
var promise = new Promise((resolve,reject)=>{
connection.query(sql,[key], function(error, results, fields) {
if(error){
reject(error)
}else{
resolve(results);
}
});
connection.end();
});
return promise;
}
module.exports = query;
})()

Angular 4 - display date from database

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.