I'm trying to query a single line from a 28k record database as a test but it isn't going through but when I load up 'localhost:3001/api/get' it stays loading, even though my connection says success? Is it actually even connecting to the db?
my data bases schema is:
id | state_name | city
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.get('/api/get', (req, res)=>{
const sqlGet = "SELECT city FROM state_city city = 'Chicago'";
db.query(sqlGet, (err, res)=>{
console.log("success");
});
});
app.listen(3001, ()=>{
console.log("running on port 3001");
});
First you must make server running. Remove that API route you had set before running server.
app.listen(3001, ()=>{
console.log("running on port 3001");
});
Now you must create database connection. Create new file dbconn.js
var mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
Now create new connection:
var new_connection = mysql.createPool(
db
);
new_connection.on('connection', function (connection) {
console.log('DB Connection established');
connection.on('error', function (err) {
console.error(new Date(), 'MySQL error', err.code);
});
connection.on('close', function (err) {
console.error(new Date(), 'MySQL close', err);
});
});
// export connection
module.exports = new_connection;
Include that connection in other file:
var db_connection = require('../dbconn');
db_connection.query(query, params, function (error, results, fields) {
//Do your query
});
Read about project structure to make your code easy to edit.
Related
Do you know why I can not manually add the value "Sasan" to mySQL server?
MarioDB is installed in PHPStorm and schema is correctly selcted.
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mysql = require("mysql");
const cors = require("cors");
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "Test123456",
database: "shoppingList-DB"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get("/test", (req, res) => {
const sqlInsert = "INSERT INTO shoppingList (itemList) VALUES ('Sasan')";
db.query(sqlInsert, (error, result) => {
console.log("error", error);
console.log("result", result)
res.send("Hello Express");
})
})
app.listen(5001, () =>{
console.log("Server is up - Port 5001");
})
The error is pretty clear Access denied for user 'root'#'localhost'. Check your credentials and user access in mysql.user table.
I'm performing CRUD operations using MYSQL and NodeJS express. Their error in deleting a record from DB, I don't know why I was getting a problem as i have copied the delete query from SQL where it is working properly. Here it is 'DELETE FROM tblltest WHERE id=?'. I manually add 'id' like 'DELETE FROM tblltest WHERE id=2' then it will delete the record from DB. Please help me out to solve this issue. Here are my lines of code.
var express = require('express');
var mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'sampledb'
});
app.delete('/:id' , function(req , resp) {
connection.query('DELETE FROM `tblltest` WHERE `id`=?' , function(error , rows , fields){
if(!error){
console.log('Successful deleted!! \n');
resp.json(rows);
}else{
console.log('Error in deleting');
}
});
})
app.listen(1337);
You need to access the id route parameter in your delete API Node method, and then also bind this id value to the delete query:
app.delete('/:id', function(req, resp) {
var id = req.params.id;
connection.query('DELETE FROM tblltest WHERE id = ?', [id],
function(error, rows, fields) {
if (!error) {
console.log('Successful deleted!! \n');
resp.json(rows);
}
else {
console.log('Error in deleting');
}
});
})
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 : 'sampledb' //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(1337, "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 delete record from mysql database
app.delete('/employees', function (req, res) {
console.log(req.body);
connection.query('DELETE FROM `tblltest` WHERE `id`=?', [req.body.id], function (error, results, fields) {
if (error) throw error;
res.end('Record has been deleted!');
});
});
I created a server.js file which looks like this.
var express = require('express'),
app = express(),
port = process.env.PORT || 3000;
app.listen(port);
console.log('todo list RESTful API server started on: ' + port)
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "**",
password: "**",
database: "test"
});
app.get('/nodeapi/getimg',function(req,res){
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM images", function (err, result, fields) {
if (err) throw err;
console.log(result[1].image);;
});
})})
When I run this file in my command terminal I get the correct result.
When I create a http.get function like this for my ionic app:
getimg(){
var url = 'http://localhost:3000/nodeapi/getimg';
this.http.get(url).subscribe(responseData => console.log(responseData));}
I get an error saying net::ERR_CONNECTION_REFUSED. I have looked everywhere but cannot seem to find it. I am using phpmyadmin for the database. Would anyone please be so kind to explain to me what I am doing wrong.
Give this example a try. Also, do you expect more than one result from your query? If not you will want to use result[0] not 1 to get the first (and maybe only) result (located at index 0).
var express = require('express');
var cors = require('cors');
var mysql = require('mysql');
var port = process.env.PORT || 3000;
var app = express();
app.use(cors());
app.options('*', cors());
var con = mysql.createConnection({
host: "localhost",
user: "**",
password: "**",
database: "test"
});
app.get('/nodeapi/getimg', function(req, res) {
con.connect(function(err) {
if(err) throw err;
con.query("SELECT * FROM images", function(err, result, fields) {
if(err) throw err;
console.log(result[1].image);
res.send(result[1].image); // send the value back to the caller.
});
})
})
app.listen(port, function() {
console.log('CORS-enabled web server listening on port 80')
})
I've tried to implement this code and terminal throws error something like this stucked in it As I've applied this code but it throws the error
"Access denied for user ''#'localhost' to database 'mydb'"
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "myusername",
password: "mypassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a database named "mydb":*/
con.query("CREATE DATABASE mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
create a config folder and create a file databaseConfig.js
var mysql = require('mysql');
config = {
host: 'localhost',
user: 'root',
password: '',
database: '<DB name>'
}
var connection =mysql.createConnection(config); //added the line
connection.connect(function(err){
if (err){
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
});
module.exports ={
connection : mysql.createConnection(config)
}
create a app.js file
var express = require('express');
var cors = require('cors');
app = express(),
app.use(cors()),
port = process.env.PORT || 3001;
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/routes'); //importing route
routes(app);
console.log('todo list RESTful API server started on: ' + port);
app.listen(port);
create a controller.js file
var config = require('../../databaseConfig.js');
var connection= config.connection
connection.query ('CREATE DATABASE mydb', function(error, results){
if (results){
console.log(results);
}
else{
console.log(error);
}
});
I'm trying to connect to remote SQL server. I do connect from SQL Management Studio without problems, but with the code below i wait like 2-3 mins to get error ECONNRESET, what's wrong? Why do I wait so much?
let mysql = require('mysql'),
express = require('express'),
bodyParser = require('body-parser'),
app = new express(),
_port = process.env.port || 3000;
let con = mysql.createConnection({
host: '***.***.***.***',
port: ****,
user: "*****",
password: "****"
});
con.connect( function (err) {
if (err) console.log(err);
console.log('connected');
})
app.get('/', (req, res) => {
res.send('ffs');
});
app.listen(_port, () => {
console.log('listening on port ' + _port);
});
The mysql version is 2.11.0 atm, but i tried with the latest one first.