I wrote this code
var http = require('http');
var express = require('express');
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'nodejs'
});
connection.connect(function (err) {
if (!err) {
connection.query('SELECT * FROM nodetest', function (err, rows) {
if (err) {
console.log(err);
return;
}
var json = JSON.parse(JSON.stringify(rows))[0];
console.log(json);
});
console.log("Database is connected");
} else {
console.log("Error connecting database");
}
});
http.createServer(function (request, response) {
response.writeHead(200, {
"Content-Type": "test/html"
});
response.end('here my data');
}).listen(7777);
and I have a problem with display the result in my localhost as i json
what is the bast way to read table and convert it to json and display in localhost
what does JSON.stringify do?
The JSON.stringify() method converts a JavaScript value to a JSON
string, optionally replacing values if a replacer function is
specified, or optionally including only the specified properties if a
replacer array is specified.
What does JSON.parse do?
The JSON.parse() method parses a JSON string, constructing the
JavaScript value or object described by the string.
So basically, one operation is the inverse of the other. And therein lies your problem:
var json = JSON.parse(JSON.stringify(rows))[0];
Since you are requiring express, I'm assuming you want to use it.
You can create an index route with app.get('/', function(req,res){}). A fast way to display your data as json from your mysql database would be:
var express = require('express');
var mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'nodejs'
});
// localhost:7777/
app.get('/', function(req, res) {
connection.connect(function(err) {
if (!err) {
connection.query('SELECT * FROM nodetest', function(err, rows) {
if (err) {
console.log(err);
return;
}
var json = JSON.parse(JSON.stringify(rows))[0];
res.send(json); // Send the JSON back as a application/json type response.
});
console.log("Database is connected");
} else {
console.log("Error connecting database");
}
});
})
app.listen(7777, function() {
console.log('Example app listening on port 7777!')
});
Related
I am struggling to wrap my head around all this backend stuff. I basically have set up an amazon mySQL server with RDS and using mySQLWorkBench I have connected my express.js with the following file:
let mysql = require('mysql');
var connection = mysql.createConnection({
host: "",
user: "admin",
password: "",
});
connection.connect(function(err) {
if (err) throw err;
connection.query('CREATE DATABASE IF NOT EXISTS main;');
connection.query('USE main;');
connection.query('CREATE TABLE IF NOT EXISTS cars(id int NOT NULL AUTO_INCREMENT, manufacturer varchar(100), model varchar(100), price int, PRIMARY KEY(id));', function(error, result, fields) {
console.log(result);
});
connection.end();
});
module.exports = connection;
I already have my table set up in mySQLWorkbench, and and the connection is fine if I user the following in my server file:
connection.connect(function(err) {
if (err) {
console.error('Database connection failed: ' + err.stack);
return;
}
console.log('Connected to database.');
});
connection.end();
However in my Index.js, I am trying to create a post endpoint (im still very new to this and not sure where I should start etc, but I was following this tutorial: https://stackabuse.com/using-aws-rds-with-node-js-and-express-js/ ).
index.js:
const express = require('express');
const app = express();
const port = 3000;
const connection = require("./server");
app.listen(port, () => console.log("listening on port 3000") + port )
const dummyData = [
{manufacturer: "volvo", model: "1st", price: 300},
{manufacturer: "fiat", model: "500", price: 500},
];
app.post('/cars', (req, res) => {
if (req.query.manufacturer && req.query.model && req.query.price) {
console.log('Request received');
connection.connect(function(err) {
connection.query(`INSERT INTO main.cars (manufacturer, model, price) VALUES ('${req.query.manufacturer}', '${req.query.model}', '${req.query.price}')`, function(err, result, fields) {
if (err) res.send(err);
if (result) res.send({manufacturer: req.query.manufacturer, model: req.query.model, price: req.query.price});
if (fields) console.log(fields);
console.log(result)
});
});
} else {
console.log('Missing a parameter');
}
});
I am really not sure if I am doing this correctly, but when I run the file and host it, it's fine, then when I try use postman to do a post request with the following fields:
localhost:3000/cars?manufacturer=test&model=testmodel&price=2000
I get the following error:
{
"code": "PROTOCOL_ENQUEUE_AFTER_QUIT",
"fatal": false
}
My goal is here, is to have a few simple endpoints for my datastore, which is to post, retrieve and update. Any help for clarification or guides would be extremely appreicated. Thanks!
I have root endpoint who work when users enter the url like this:
http://localhost:8000/?date=2019-10-20&station=41027&daysForward=3
I want to create second root endpoint in the same file with different query but that did not work.
My code:
// Create express app
var express = require("express")
var app = express()
var mysql = require('mysql')
var express = require("express")
var cors = require('cors')
app.use(cors())
// Server port
var HTTP_PORT = 8000
// Start server
app.listen(HTTP_PORT, () => {
console.log("Server running on port %PORT%".replace("%PORT%",HTTP_PORT))
});
var con = mysql.createConnection({
host: "192.168.1.1",
port: "3456",
user: "user",
password: "pass"
});
var con2 = mysql.createConnection({
host: "192.168.1.1",
port: "3456",
user: "user",
password: "pass"
});
let aladinModel= '';
let aladinModelStations = '';
app.route('/')
.get(function(req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*');
const date = req.query.date;
const station = req.query.station;
const daysForward = req.query.daysForward;
try {
const query = `CALL aladin_surfex.Get_mod_cell_values_meteogram('${date}', ${station}, ${daysForward})`;
con.query(query, function (err, result, fields) {
if (err) throw err;
aladinModel = result;
});
res.json({aladinModel})
} catch(error){
console.log("Error query database!!!");
}
});
app.route('/stations')
.get(function(req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*');
try {
const query2 = `SELECT Station,Ime FROM stations_cells`;
con2.query2(query2, function (err, result2, fields) {
if (err) throw err;
aladinModelStations = result2;
});
res.json({aladinModelStations})
} catch(error){
console.log("Error query database!!!");
}
});
app.use(function(req, res){
res.status(404);
});
I guess this is not the right way to route pages but I hope someone can explain to me with an example how I could fix the code - so when a user enters:
http://localhost:3000/stations
the data should be loaded.
I see this error when I try to open this link.
[nodemon] starting `node server.js localhost:8000`
Server running on port 8000
Error query database!!!
This query
SELECT station, ime
FROM stations_cells
on the second root point is fine. I try to SELECT with HeidiSQL and database return the data values ?
Where is the problem for the second root point ?
That might not be the case, but here's the suggestion (which doesn't fit in comment section)
app.route('/')
.get(function(req, res) {
// omitted
});
app.route('/stations')
.get(function(req, res) {
// omitted
});
I've been using mongoDB forever. How do I switch over to MySQL? Currently, I have no idea where to look. Should I use MySQL workbench? PGAdmin4? How the heck do I go about doing this or learning to do this?
Try the JavaScript mysql package. It's the most popular package for working with MySQL in JavaScript, and the GitHub readme should walk you through most steps on using it.
If you'd like a second option, I've also had experience with the node-mysql package (which depends on the mysql package). It's a bit simpler to use and it worked great for me as well.
I added in this post, How to work with MySQL in Nodejs.
Step 1: Create table in you MySQL DB:
CREATE TABLE IF NOT EXISTS `employee` (
`id` int(11) NOT NULL COMMENT 'primary key',
`employee_name` varchar(255) NOT NULL COMMENT 'employee name',
`employee_salary` double NOT NULL COMMENT 'employee salary',
`employee_age` int(11) NOT NULL COMMENT 'employee age'
);
Step 2: Install all package using this command :
npm install --save mysql express body-parser
Step 3: Create app.js File in same directory
var http = require("http");
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
//start mysql connection
var connection = mysql.createConnection({
host : 'localhost', //mysql database host name
user : 'root', //mysql database user name
password : '', //mysql database password
database : 'dummy_db' //mysql database name
});
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected...')
})
//end mysql connection
//start body-parser configuration
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
//end body-parser configuration
//create app server
var server = app.listen(3000, "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)
});
//rest api to get all results
app.get('/employees', function (req, res) {
connection.query('select * from employee', function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
});
//rest api to get a single employee data
app.get('/employees/:id', function (req, res) {
console.log(req);
connection.query('select * from employee where id=?', [req.params.id], function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
});
//rest api to create a new record into mysql database
app.post('/employees', function (req, res) {
var postData = req.body;
connection.query('INSERT INTO employee SET ?', postData, function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
});
//rest api to update record into mysql database
app.put('/employees', function (req, res) {
connection.query('UPDATE `employee` SET `employee_name`=?,`employee_salary`=?,`employee_age`=? where `id`=?', [req.body.employee_name,req.body.employee_salary, req.body.employee_age, req.body.id], function (error, results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
});
//rest api to delete record from mysql database
app.delete('/employees', function (req, res) {
console.log(req.body);
connection.query('DELETE FROM `employee` WHERE `id`=?', [req.body.id], function (error, results, fields) {
if (error) throw error;
res.end('Record has been deleted!');
});
});
Step 4: Start the server using this command:
node app.js
Follow this link if you face any issue.
I'm pretty new to javascript but I have a REST API I'm running on a LAN network. I have a MySQL database I'm trying to save a HTTP POST body to in JSON format. My js code will print the data as "result" for me but will not save it when it is sent from Postman, however if I hard code a fake entry into it as "var result = {JSON format entries}" it will then be able to be saved to MySQL. Here is my code:
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
const { parse } = require('querystring');
var mysql = require("mysql");
var app = express();
var port = process.env.port || 8080;
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '*******',
database : 'userInfo'
});
connection.connect(function(err) {
if (err) throw err
console.log('You are now connected with mysql database...')
})
app.post('/licence', function (req, res) {
collectRequestData(req, result => {
console.log(result);
connection.query('INSERT INTO licence SET ?',result, function (error,
results, fields) {
if (error) throw error;
res.end(JSON.stringify(results));
});
res.end(`Parsed data belonging to ${result.fname}`);
});
});
function collectRequestData(request, callback) {
const FORM_URLENCODED = 'application/json';
if(request.headers['content-type'] === FORM_URLENCODED) {
let body = '';
request.on('data', chunk => {
body += chunk.toString();
});
request.on('end', () => {
callback(parse(body));
});
}
else {
callback(null);
}
}
I'm pretty sure I don't need this line "res.end(Parsed data belonging to ${result.fname});" but what I am trying to figure out here is how to save result to the licence table in mysql. This is what console.log(result) prints: { '{"hash":"TestHaaaash", "size":13, "difficulty":47, "time":null, "timestamp":null, "date":null}': '' } I think this should be slightly different but I'm not sure how it should be or how to change it
In collectRequestData try chaging
request.on('end', () => {
callback(parse(body));
});
to
request.on('end', () => {
callback(JSON.parse(body));
});
I am new to node.js and am trying to learn how to connect to mysql database from ejs file. I tried to search for sample code however the code is not working. Can someone please check it out for me. Thank you.
function loaddata() {
var sql = require("mysql");
var con = mysql.createConnection({});
con.connect(function (err) {
if (err) {
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
con.query('update students set name="sus" where email="smn14#mail.aub.edu"', function (err, rows) {
if (err) throw err;
console.log('Data received from Db:\n');
console.log(rows);
});
con.end(function (err) {
// The connection is terminated gracefully
// Ensures all previously enqueued queries are still
// before sending a COM_QUIT packet to the MySQL server.
});
}
The create connect is worst.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows,
fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution); });
connection.end();
From this example, you can learn the following:
Every method you invoke on a connection is queued and executed in sequence.
Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the
mysql server.
Docs
I now understand the process of server/clients. Makes sense, otherwise you would be able to see the database passwords stored in Client.js. :-)
But, there is one way that works for me. The client call a javascript-function and send a message to the server. The server receives this message and starts a database query. Send the result to all clients via socket.io
At the client in the file.ejs
<script type='text/javascript'>
let socket = io.connect();
function getSql(userId) {
socket.emit('start-new-sql-querie',{
userId: userId
});
}
socket.on('new-sql-result', function (data){ // listen for the new sql result
console.log(data.userStatus); // foo something with the new data
})
</script>
<button onclick="getSql(1)">Test sql query</button>
database connection.js at server side
const connection = {
connectionLimit: 10,
host: "localhost",
user: "Abc",
password: "1234",
database: "d001",
multipleStatements: true
};
module.exports = connection;
yourapp.js at server side
const express = require('express');
const port = process.env.PORT || 1234;
const app = express();
const server = require('http').createServer(app);
const mysql = require('mysql2');
const config = require('./routes/connection'); // SQL-Connection
const pool = mysql.createPool(config);
let io = require('socket.io')(server);
io.sockets.on('connection', function(socket) {
socket.on('start-new-sql-querie', function(data) { // listen from the clients
let user_id = data.userId;
sql_test.getConnection((error, connection) => { // Connect to sql database
console.log("user_id: ", user_id)
connection.query(`SELECT * FROM user WHERE id='${user_id}'`, (err, result) => {
socket.emit('new-sql-result',{ // send sql result-status to all clients
userStatus: result.result[0].status
})
})
connection.release();
})
});
})