Cannot Connect to MySQL with NodeJS, but can via Windows Powershell - javascript

I've seen many variations of this question, but I couldn't find an answer - and in fact am not sure where to look for logs that could help me. Here's the situation.
I was following this tutorial
I have the following in a file called "server.js":
const mysql = require("mysql");
const express = require("express");
const bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json());
var mysqlConnection = mysql.createConnection({
host: "localhost",
user: "root",
password: "confidential666!",
database: "blunt",
multipleStatements: true
});
mysqlConnection.connect((err)=>{
if(!err){
console.log("Connected");
}
else{
console.log("connect failed");
console.log("big woof");
}
});
app.listen(3000);
console.log("did run");
I run this code with "nodemon server.js"
However, my console shows me "connect failed" and "big woof".
I then tried to connect to my database with mysql.exe with the same credentials, and could connect to "blunt" just fine.
Port is missing from my connection, but documentation suggests 3306 is the default and that's what my server is using. Adding it made no difference. Any idea on how I can figure out why I can't get my nodemon to connect to my database?

Related

Connect to postgres with nodeJS

Im struggling to create API call to my database from node.js.
i have a postgres instance on Centos with multiple databases and table.
im trying to get table name "test_reslts" from database "sizing_results".
when the url, its just the server ip and port like http://{SERVER IP}:3300/
this is output -
"Cannot GET /"
when adding the table name or db name and table name, the request isn't completed and not output.
my code -
db_connection
const {Client} = require('pg')
const client = new Client({
user: 'postgres',
database: 'sizing_results',
password: 'password',
port: 5432,
host: 'localhost',
})
module.exports = client
api.js
const client = require('./db_connection.js')
const express = require('express'); // To make API calls
const app = express();
app.listen(3300, ()=>{
console.log("Server is now listening at port 3300");
})
client.connect();
app.get('/test_results', (req, res)=>{
client.query(`select * from test_results`, (err, result)=>{
if(!err){
res.send('BLABLA')
res.send(result.rows);
}
});
client.end;
})
Base on your answer to my comment I think it's not a DB connection problem.
It seems to be link to your routing, because it seems node never reach the inside of your route.
Are you sure you are calling the good route (http://localhost:3300/test_results) with no typo ? And with the good protocol (GET) ?

React: Trying to connect index.js to database but its not working

So i built a frontend where you can fill in a movie name, a review and submit it to a database. Now im trying to connect a mysql database i created to the index.js , so that it gets filled with the first entry. Im trying to accomplish it like this:
const express = require('express');
const app = express();
const mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password:"password",
database:'CRUDDatabase',
});
app.get('/', (req, res) => {
const sqlInsert = "INSERT INTO Movie_Reviews(movieName, movieReview) VALUES (1,'inception', 'good movie');"
db.query(sqlInsert, (err, result) =>{
res.send("change done");
});
})
app.listen(3001, () => {
console.log("running on port 3001")
})
But somehow the frontend gets the text ive send "Change done" but the database still doesnt show any entries. Any ideas where my mistake may be? Is it a code mistake or does it have to do with me db configuration. In mysql workbench i just created a default connection without changing anything.
EDIT: The Error seems to be the following:
Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
EDIT:
The following comment here solved my problem:
Execute the following query in MYSQL Workbench ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'password'; Where root as your user localhost as your URL and password as your password Then run this query to refresh privileges: flush privileges; Try connecting using node after you do so. If that doesn't work, try it without #'localhost' part.
I think you have an error in your code but you are not showing it as you don't test in err variable, try this code in order to show what error you are getting:
const express = require('express');
const app = express();
const mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password:"password",
database:'CRUDDatabase',
});
app.get('/', (req, res) => {
const sqlInsert = "INSERT INTO Movie_Reviews(movieName, movieReview) VALUES (1,'inception', 'good movie');"
db.query(sqlInsert, (err, result) =>{
if(err) {
console.log(err);
res.send(err.toString());
}
res.send("change done");
});
})
app.listen(3001, () => {
console.log("running on port 3001")
})
So as Med Amine Bejaoui pointed out in a comment, the solution is:
Execute the following query in MYSQL Workbench ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'password'; Where root as your user localhost as your URL and password as your password Then run this query to refresh privileges: flush privileges; Try connecting using node after you do so. If that doesn't work, try it without #'localhost' part.

Can't send requests to server using Postman anymore

I'm using both Ubuntu and Visual Studio Code to launch my server program, they were both sucessfully taking and sending back replies from Postman a few days ago. The server code runs fine, and says the server is up and running at https://loccalhost:8080
But when I try to send a GET request from Postman, I get this error from Postman:
This is the environment I'm using:
And this is the error I get from my server program when it gets a request:
How ther server is configured:
require('dotenv').config()
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.set("port", 8080);
app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.urlencoded({ extended: true }));
const Pool = require("pg").Pool;
const config = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: "taskfour"
};
const pool = new Pool(config);
//HELLO WORLD
app.get("/hello", (req, res) => {
res.json({msg: "Hello, World!"});
});
app.listen(app.get("port"), () => {
console.log(`Find the server at http://localhost:${app.get("port")}`);
});
The server had previously been working fine, Postman was sending requests, doing tests, and my code was passing them. I didn't change much in the meanwhile, I'm not sure what changed. I've tried turning off my proxy server on Postman, but it hasnt' helped. Any help would be greatly appreciated.
Looks like the HTTP listening code is missing, for example:
app.listen(8080, function () {
console.log('App listening on port 8080.');
});
Wow, I didn't realize the postgres service wasn't running. I just needed to enter the command "sudo service postgresql start" in my terminal, and the requests work again.

AJAX - Using ajax to call mySQL data with Node.js and Express

I am new to programming for Web Applications
I am making a web service app using AJAX, mySQL, Node.js and Express.
I have made a database for mySQL and have connected it.
The problem i am facing is using AJAX to call mySQL data and to display it on my web-page using Node.JS / Express.
The code i have for the server and database connection:
app.js
var express = require('express');
var http = require('http');
var path = require('path');
//Import mySQL module
var mysql = require('mysql');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
//Connection object using credentials
var con = mysql.createConnection({
host: "localhost",
user: "data",
password: "database",
database: "mydb"
});
//Connecting to the database
con.connect(
function(err){
if (err) throw err;
console.log("Database Connected");
}
);
con.end();
app.use(express.static(path.join(__dirname, '/public')));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080);
I will be creating a new js file to contain my AJAX code, however i do not know how to start constructing it. My aim is to use Node.js/Express to call information from my database into a table which i have formed using Bootstrap
Thanks

nodejs express mongoose connect to db error

I use nodejs express and mongoose to connect mongodb,I've created a config.js in root folder.I am trying to exports db connect in db.js and trying to import in adminController.js
But when I run the server and refresh the browser ,it log me some errors and not log my log in terminal.
config.js
module.exports = {
cookieScret:'ThreeKingdoms',
db:'threekingdoms',
host:'localhost',
port:27017
}
db.js
var mongoose = require('mongoose'),
config = require('../config'),
connection = mongoose.connection;
module.exports = function(mongoose){
return mongoose.connect('mongodb://'+config.host+'/'+config.db);
}
adminController.js
var express = require('express'),
router = express.Router(),
mongoose = require('mongoose'),
mainInfo = require('../models/admin'),
db = require('../models/db');
router.get('/', function(req, res) {
res.render('admin', { title: 'hey im here!how are you' });
db.on('error',console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log(db)
});
console.log(db)
});
router.post('/',function(req,res,next){
//console.log(req.body)
var mainInfo = mongoose.model('mainInfo');
})
module.exports = router;
question files is in red box
terminal error
I am new to nodejs,so please help me,Thanks
First, it seems that you don't have kerberos installed. Please run npm install kerberos.
Also, the line
Can't set headers after they're sent
Suggests you're trying to modify/send the response after it was already sent back to the client, and that's the error you're getting.
finally it is work now,but it doesn't matter with 'kerberos' ,it is i use wrong way to export my module.terminal still log me 'kerberos undefined' but web can work,i think maybe some time i will try to figure this question out.thanks for your attention

Categories

Resources