Database connection error with nodejs and xampp mysql - javascript

So ive been trying to make a login form using nodejs and xampp mysql but after entering details from the table and clicking on login button the page keeps loading and nothing happens.... i cant quite figure it out.. This is how my directory looks.
My html code is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Krishi Mitra Admin Login</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Exo:wght#200&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/assets/css/logstyle.css">
<script src="assets/js/logmain.js"></script>
</head>
<body>
<section>
<div class="img">
<img src="assets/imgs/bg.jpg">
</div>
<div class="content">
<div class="form">
<h2>Login</h2>
<form action="/" method="post">
<div class="input">
<span>Username</span>
<input type="text" id="username">
</div>
<div class="input">
<span>Password</span>
<input type="password" id="password">
</div>
<div class="input">
<div class="submit">
<input type="submit" value="Sign In">
</div>
</div>
<span id="error"></span>
</form>
</div>
</div>
</section>
</body>
</html>
and app.js file is:
const express = require('express')
const bodyParser = require('body-parser')
const mysql = require('mysql')
var path = require('path')
const app = express()
const port = process.env.PORT || 3306;
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodejs'
})
connection.connect(function(error){
if (error) throw error
else console.log("connected to the database successfully!")
});
app.get("/",function(req,res){
res.sendFile(__dirname + "/index.html");
})
app.use(express.static(path.join(__dirname, 'public')));
app.post("/", function(req,res){
var username = req.body.username;
var password = req.body.password;
connection.query("select * from loginuser where user_name = ? and user_pass = ?",[username,password],function(error,results,fields){
if (results.length > 0) {
res.redirect("/dash.html");
} else {
res.redirect("/");
}
res.end();
})
})
app.get("/welcome",function(req,res){
res.sendFile(__dirname + "/dash.html")
})
app.listen(port, () => console.log(`Listening on port ${port}`))
I tried running xampp server using the admin panel on port 3306 but it wont let the node file run and shows the error that port is already in use..
I want this to open the dash.html file after login

The problem with your current setup is that you're telling your node server to listen for incoming connections on port 3306, and you're using that same port to try and connect to the database.
Change your app.js code like this, and it should work.
... // rest of the code
const port = process.env.PORT || 1234; // or any port not already in use
.... // rest of your code
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodejs',
port : 3306 // <== add the port for database connection
})
For this to work, you should have Xampp in the background, running the MySQL module on port 3306. Of course, if you change your port in Xampp (for whatever reason), you'd need to change it in your app.js file as well.

Related

res.send Not sending any data - Express.js

So I am working on this calculator app using Express.js and when I use the res.send Method I am not receiving any kind of response now.
I expect my webpage to send me the sum as in the calculator.js file.
I am using nodemon as well.
This is HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
</head>
<body>
<h1>Calculator</h1>
<form method="POST">
<input name='num1' placeholder='num1' type='text'>
<input name='num2' placeholder='num2' type='text'>
<button
type="submit" name="submit">Calculate</button></form>
<h1 class='answer'></h1>
</body>
</html>
This is calculator.js
const express = require('express');
const app = express();
const port = 3000;
const bodyParser = require("body-parser");
const {
json,
urlencoded
} = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html")
});;
app.post("/", function (req, res) {
console.log(req.body);
var num1 = Number(req.body.num1);
var num2 = Number(req.body.num2);
var sum = num1 + num2;
res.send(sum);
});
app.listen(port, () => console.log(`Example app listening on port port!`))
you can't use res.send() to send number, it will be sent as a http status code. You can simply convert calculated sum to string and then send it:
res.send(sum.toString())
res.send has been deprecated in the latest version of Express (4.17.1).
Using res.sendStatus instead solved my problem.

Socket.io Connection Event Not Triggering

I am new to using socket.io and I have tried to set up a basic functionality according to the docs and youtube tutorials. My program is supposed to console log "New socket connection" when I navigate to the index page. However, the event is not triggering. Am I missing something? Thanks!
My app.js file
const express = require("express");
const socket = require("socket.io");
const http = require("http");
const moment = require("moment");
const app = express();
const server = http.createServer(app);
const io = socket(server);
app.set("view engine", "ejs");
// Set static folder
app.use("/public", express.static("public"));
app.get('/', (req, res) => {
console.log("Reached index page")
res.render("index")
});
app.get('/room', (req, res) => {
console.log("Reach room page")
res.render("room")
});
// Run when a client connects
io.on("connection", (socket) => {
console.log("New socket connection")
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running. Navigate to localhost:${PORT}`));
My index.ejs file
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<link rel="icon" href="../public/">
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="../public/index/css/index.css" />
</head>
<body>
click here
<script>
var socket = io(); // this line is supposed to be sufficient to trigger
// the socket connection
</script>
<script src="../routes/index.js"></script>
<script src="/socket.io/socket.io.js"></script>
</body>
</html>
The error resulted from my naming my variable 'socket' when importing the socket.io dependency. The socket param in the line 'io.on("connection", (socket)' is supposed to reference another socket variable not the one that I created. Common practice is to name the dependency variable 'socketio' instead of 'socket'

Post Request not Calle

So I'm learning node.js and I've hit a wall. My post request is not getting triggered.
var http = require('http');
var express = require('express');
var app = express();
var fs = require('fs');
Setting up server
var server = http.createServer(function(req,res){
console.log('request was made: ' + req.url);
if (req.url === '/home' || req.url === '/'){
fs.readFile("./index.html",null,function(error,data){
if (error) throw error;
res.write(data);
res.end();
});
} else {
console.log("404");
}
})
The post-request that refuse to work
app.post('/test', function(req,res){
console.log("post req came thru");
})
Listening...
server.listen(8080)
HTML
<!DOCTYPE html>
<html>
<head>
<title>CRUD App</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="/test" method="POST" >
<input type="text" name="test"></input>
<button>Submit</button>
</form>
</body>
</html>
You need to pass the Express app as a parameter to the http.createServer function otherwise it won't be handling any of your requests. Either that, or use the actual app.listen method:
app.listen(port, () => console.log(`Example app listening on port ${port}!`))

How to link an existing Angular 2 app to Nodejs Server?

I have an Angular 2 app with this structure :
Structure of my Angular app
Then in server side :
Structure of server app
I see that there is 2 module dependencies folders, but I don't know which one I sould keep.
Here is my index.js file :
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
// Get our API routes
//const api = require('./server/routes/api');
const app = express();
// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'client/portfolio')));
// Set our api routes
//app.use('/api', api);
// Catch all other routes and return the index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client/portfolio/src/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3001';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`API running on localhost:${port}`));
When I start server I get this message :
Loading AppComponent content here ...
But it stops here and doesn't render the Angular application.
index.html file :
<!DOCTYPE html>
<html>
<head>
<title>Angular QuickStart</title>
<base href="/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<link href="node_modules/#angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/hammerjs/hammer.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('main.js').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading AppComponent content here ...</my-app>
</body>
</html>
Here's a good example of integrating AngularJS with NodeJS [open tutorial]
The trick is in this block
/* GET home page. */
router.get('/', function(req, res, next) {
res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});

Using the Express.js app.post request is not working

I am having an issue with the Express.js library.
I have been trying to set up a basic post request with the route.
I have installed and using body-parser for the post data.
If I specifically add app.post it does not work but if I use GET or app.all it works just fine with my post data.
Could some one take a look at my code and see what i could be doing wrong? Also just for a further clarification i will be splitting all this up later on i just have the data base connection and every thing else in one file to test things.
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
var getuser_Information;
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/data/db/');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
// yay!
});
//testing the mogno db for createing a new table schema for a user login using the mognose api example
var UserSchema = mongoose.Schema({
name:String
});
var usersinfo = mongoose.model('Userinformation', UserSchema);
//sets up the log in
app.post('/',function(req, res) {
getuser_Information = new usersinfo({ name:req.body.usernames});
getuser_Information.save(function (err,getuser_Information) {
if (err) return console.error(err);
console.log(silence);
});
res.render('def',{
firstnames:getuser_Information
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<h1>Hello, world!</h1>
<form class="navbar-form navbar-left" role="search" method="post">
<div class="form-group">
<input type="text" class="form-control" name="usernames">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<h1>Hello <%= firstnames %></h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
So i was not routing the correct information and figured out the diffrences of when using app.all. here is the code that i have now.
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
var getuser_Information;
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/data/db/');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
// yay!
});
//testing the mogno db for createing a new table schema for a user login using the mognose api example
var UserSchema = mongoose.Schema({
name:String
});
var usersinfo = mongoose.model('Userinformation', UserSchema);
//sets up the log in
app.get('/',function(req, res) {
res.render('def',{
firstnames:""
});
});
app.post('/run',function(req, res) {
getuser_Information = new usersinfo({ name:req.body.usernames});
getuser_Information.save(function (err,getuser_Information) {
if (err) return console.error(err);
else
res.render('def',{
firstnames:getuser_Information
});
});
});
process.on('uncaughtException', function (err) {
console.log("\n\r *Uncaught Exception event* \n\r")
console.log(err);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<h1>Hello, world!</h1>
<form action="/run" class="navbar-form navbar-left" role="search" method="POST">
<div class="form-group">
<input type="text" class="form-control" name="usernames">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<h1>Hello <%= firstnames %></h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
app.post('/',function(req, res) {
getuser_Information = new usersinfo({ name:req.body.usernames});
getuser_Information.save(function (err,getuser_Information) {
if (err) return console.error(err);
else
res.render('def',{
firstnames:getuser_Information
});
});
});
Node.js is asynchronous.

Categories