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.
Related
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 make a node JavaScript app and deploy it on cPanel using SSH.
App is working fine without database but when I connect the app with database on cPanel (GoDaddy) it takes times and shows the message "Error establishing a database connection".
My connection code
const mysql = require('mysql');
const express = require('express');
const app = express();
var pool = mysql.createConnection({
host: 'localhost',
user: '<MY_USER_NAME>',
password: '<MY_PASSWORD>',
database: '<DB_NAME>'
});
pool.connect(function(err) {
if (err) throw err;
else{
console.log("Connected!");
}
});
module.exports = pool;
route where DB interact,but lost the connection.
app.post('/loginn', (req, res) => {
var id = req.body.id
console.log("user_id= "+id);
var sql = "select * from users where id NOT IN ('" + id + "') ";
pool.query(sql, function (err, rows) {
if (err) throw err;
else {
res.render('allusers', {
users: rows,
user_id:id
})
}
});
});
This answer is going to take the form of a debugging journey, because that's the only way I can see to get to the bottom of your issue.
Let's do a dead-simple representation of your app to make sure that you can send a query to MySQL and receive a response from a route-handler in Express. Setup your app like this:
const mysql = require('mysql');
const express = require('express');
const app = express();
const PORT = // define the PORT for your host
var connection = mysql.createConnection({
host: 'localhost',
user: '<MY_USER_NAME>',
password: '<MY_PASSWORD>',
database: '<DB_NAME>'
});
connection.connect(function(err) {
if (err) console.error(err);
console.log("Connected!");
});
app.get('/db-test', (req, res, next) => {
var id = // fill in a user_id that you know exists
var sql = `SELECT * FROM users WHERE id NOT IN ('${id}') `;
console.log(sql); // confirm you are sending the sql request you believe you should be sending
connection.query(sql, function (err, results, fields) {
if (err) console.error(err);
console.log(`results: ${results}\nfields: ${fields}`);
});
});
app.listen(PORT);
And then hit the route /db-test from your app, and see what happens. If this works, then we will have at least proved that you CAN make requests between Express and MySQL. Right now, I'm not sure you can, so I'm not sure what to debug.
I'm working with Express.js and mysql package to create my apis, but i can't make a post.
This is my code so far:
const express = require('express');
const mysql = require('mysql');
const config = mysql.createConnection({
host: theHost,
port: thePort,
user: theUser,
password: thePass,
database: theDB,
});
const app = express();
config.connect(function(err){
if(!err) {
console.log("Success");
} else {
console.log("Error trying to connect");
}
});
app.get("/api/InternalAccess", function(req, res){
config.query('SELECT * from InternalAccess', (error, result) => {
if (error) throw error;
res.send(result);
});
});
app.post("/api/internalAccess", function(req, res){
var info = { User: req.body.User, Password: req.body.Password, CreationDate: req.body.CreationDate };
config.query('INSERT INTO InternalAccess SET ?', info, (error, result) => {
if (error) throw error;
res.send(result);
});
});
app.listen(3000);
I have no problems with get, it works fine, but to make post from postman, i get the error: " Cannot read property "User" of undefined". Am i avoiding something? I'm really new using mysql package.
My db is MySQL Workbench, and as i said, i'm using Node.js, Express.js and mysql package.
Hope you can help me. Thanks in advance
In order to have req.body populated automatically, you have to use some body-parser middlewares, like:
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
Of course, there can be multiple other causes (like, you're not constructing the request properly in postman), but the lack of setting the middlewares is the first place I'd fix.
Seems like req.body is null. I think you might just be missing the body-parser in your app.js.
var bodyParser = require('body-parser');
var app = express();
// parse application/json
app.use(bodyParser.json())
see other examples here: https://expressjs.com/en/resources/middleware/body-parser.html
I have a folder called NEsql, located in a folder called sqlnames1. Inside the NEsql folder, I have the following files.
sqlcreatedb.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a database named "mydb":*/
con.query("CREATE DATABASE names", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
sqlcreatetable.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "names"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a table named "customers":*/
var sql = "CREATE TABLE people (id INT AUTO_INCREMENT PRIMARY KEY, firstName VARCHAR(255), lastName VARCHAR(255))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
sqlinsertvalues.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "names"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO people (firstName, lastName) VALUES ?";
var peoplenames = [
['Vedant', 'Apte'],
['Vedant', 'Savalajkar'],
['Vinay', 'Apte'],
['Varda', 'Apte'],
['Mihir', 'Wadekar'],
['Mihir', 'Kulkarni'],
['Eesha', 'Hazarika'],
['Eesha', 'Gupte'],
['Raunak', 'Sahu'],
['Hritvik', 'Agarwal'],
['Mahima', 'Kale'],
['Shivani', 'Sheth'],
['Arya', 'Chheda'],
['Diya', 'Shenoy']
];
con.query(sql, [peoplenames], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
});
All of these files work, as I am able to complete all the tasks and successfully receive all the corresponding console.log statements. However, I am unsure as to how I am supposed to connect these files to the app.js file located inside the sqlnames1 folder. Anyone know how to do this?
Here is my app.js file.
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
What you're trying to do could simply just be the content of the app.js file you could require your package there and run these functions. However if going that route is what you choose it you could store them in a variable and then use a module.export like so
variable_name = [desired content to export]
module.export = variable_name
If you'd like to go about building a database through separate files than your app.js you should look at the package sequelize. This is more along the lines of you're trying to do.
https://www.npmjs.com/package/sequelize
Responding to your comment if you are trying to build a db upon running app.js. You are again better off looking at an ORM of some sort that will do it better than the mysql package. With it you can import the db to your app.js and simply use
require('path to db')
then using the db how you see fit, but again building your db in this way will be difficult to do as you would have to run
node filename.js
for every single one, so again if not sequelize i would strongly recommend looking at another ORM that will get this job done for you much faster and easier. As soon as you run your app.js it will build and then run, the mysql package is not the best tool to use for what it seems you are trying to do.
I just started to learn nodejs with express framework.In my app there are two pages app.js and db.js..I need to post data from form and insert to register table
In db.js
var mysql = require('./node_modules/mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'nodeapp'
});
connection.connect(function (err) {
if (err)
throw err;
});
module.exports = connection;
// In my app.js page
var express = require('./lib/express');
var app = express();
var bodyParser = require('body-parser')
var db = require('/db');
app.get('/', function (req, res) {
res.sendFile('/NodeProj/views/' + 'index.html');
});
/** bodyParser.urlencoded(options)
* Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST)
* and exposes the resulting object (containing the keys and values) on req.body
*/
app.use(bodyParser.urlencoded({
extended: true
}));
/**bodyParser.json(options)
* Parses the text as JSON and exposes the resulting object on req.body.
*/
app.use(bodyParser.json());
app.post('/process_form', function (req, res) {
var response = {
"firstname": req.body.fst_name,
"email": req.body.fst_email,
"password": req.body.fst_password
};
var query = connection.query('INSERT INTO register SET?',response,function(err,result){
if(err) throw err;
if(result) console.log(result);
});
res.end(JSON.stringify(response));
});
app.listen(8081);
But when I run the code I got the following error
Refference error: connection is not defined
Please help me .Thanks in advance.
As mentioned in the comments, you've called connection db.
So if you replace var db = require('/db'); with var connection = require('./db'); then your connection will be defined.