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

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

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) ?

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

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?

Socket.io 404 Not Found

For some reason I keep getting "http://127.0.0.1:3000/socket.io/socket.io.js" 404 not found when I look under chrome developer tools network. I have spent over an hour trying to understand why this isn't working because it was working fine before and I didn't think I changed anything.
Server:
var express = require('express'),
session = require('express-session');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var MongoStore = require('connect-mongo')(session);
var sessionMiddleware = session({
resave: false,
saveUninitialized: false,
secret: 'secret',
store: new MongoStore({url: "mongodb://localhost:27017/database"})
});
app.use(sessionMiddleware);
io.use(sessionMiddleware, function(socket, next) {
sessionMiddleware(socket.request, socket.request.res, next);
});
io.sockets.on('connection', function (socket) {
console.log("Socket connected");
});
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.render('index');
});
app.listen(3000);
console.log('listening');
Pug File:
html
head
script(src="http://127.0.0.1:3000/socket.io/socket.io.js")
script(type='text/javascript', src='../javascripts/chat.js')
body
Client javascript:
try {
var socket = io.connect('http://127.0.0.1:3000');
} catch(e) {
console.log(e);
}
Change this:
app.listen(3000);
to:
server.listen(3000);
app.listen() creates a new and different server so the server that you have socket.io attached to is not the one that is actually listening and thus your socket.io server is not live and not able to handle the /socket.io/socket.io.js request or the incoming connection if the script file didn't first fail to load.
See this answer for more details on what app.listen() does and why it isn't what you want the way your code is laid out:
websockets, express.js and can’t establish a connection to the server
Note, you could use app.listen(), but you'd have to not create your own server and you'd have to capture the return value from app.listen() and use that as the server you pass to socket.io initialization:
var app = express();
var server = app.listen(3000);
var io = require('socket.io')(server);
Which is not quite how your code is structured (but you could rearrange things to do it this way).

nodeJs connection with MySql for androidStudio

i'm trying to connect Mysql with a files java-script by nodejs.
But i want my server apache send my new data automatically to my app android.
For this I have a table in my database who have for name antenne who return the differents values of this table.
I have already do a script php for connect my app android and my database but with a script php isn't a callback server
Indeed i want my server push the data in the app android and not the app android who ask the data to my server
My script java
var express =require('express');
var mysql=require('mysql');
var app=express();
var connect = mysql.createConnection({
//properties...
host: 'localhost',
user:'root',
passeword;'root',
database'Antenne',
});
connection.connect(function(error){
if(!!error){
console.log('Error');
}else{
console.log('Connected');
});
app.get('/',function(req,resp){
//aboutmysql
connection.query("SELECT *FROM antenne"function(error,rows,fields))
if(!!error){
console.log('Error in the query');
}else{
console.log('Sucessful query');
});
app.listen(80);

Building an API with node and express, how to get json data from a url?

I’m building an API for a SPA built with Angular 2, for this app I have a stand alone API and than an Angular 2 app. So they are on built on two separate node.js servers. I’m using node.js and express along with 'express-connection' and 'mysql' modules to build a secure API to handle login and registration with JWT’s (json web tokens), along with other tasks of course. So I’ve successfully built this API so I can access data with my Angular 2 app via a URL. I can use the URL ’localhost:3000/data’ to access a json data object from my Angular 2 app running on 'localhost:3001/'. However, I also need the API to have access to this data object (an array of users) once the data becomes available. What is the best way to approach/accomplish this task? The only way I can think of now is to have a setTimeout function that waits for the app to load than uses an http get to grab the data from the url. There must be a cleaner way of accomplishing this task. Heres some code I have working, basically a simple node server running express. I'm somewhat new with building API's and Angular 2 concepts so any help is greatly appreciated.
app.js
/** Dependencies **/
var logger = require('morgan'),
cors = require('cors'),
http = require('http'),
express = require('express'),
errorhandler = require('errorhandler'),
dotenv = require('dotenv'),
bodyParser = require('body-parser');
/** Setup **/
var app = express();
dotenv.load();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.use(function(err, req, res, next) {
if (err.name === 'StatusError') {
res.send(err.status, err.message);
} else {
next(err);
}
});
if (process.env.NODE_ENV === 'development') {
app.use(logger('dev'));
app.use(errorhandler())
}
/** Requires **/
require('./config/sql.js')(app);
require('./config/routes.js')(app);
/** Port **/
var port = process.env.PORT || 3001;
http.createServer(app).listen(port, function (err) {
console.log('listening in http://localhost:' + port);
});
routes.js
// routes.js
module.exports = function(app) {
var query = require('./query.js')(app);
app.get('/data', function(req, res) {
query.getData(req,res);
});
};
sql.js
var connection = require('express-myconnection');
var mysql = require('mysql');
module.exports = function(app){
app.use(
connection(mysql,{
host : 'localhost',
user : 'root',
password: ‘password’,
port : 3306,
database: ‘my_project’
}, 'request')
);
};
query.js
// DB Queries
module.exports = function(app){
return {
getData: function(req, res) {
req.getConnection(function(err,connection){
connection.query('SELECT * FROM users',function(err,rows){
// console.log("success: ", rows);
res.json(rows);
});
});
}
}
};
user.js
setTimeout(function(){
// http.get function to call to API and grab data and create variable
},500);
// this is where I need an array of users that I get from a mysql database for login and registration logic
var users = [];
I'm not sure I got why you need the Angular code to talk to a different UrL but I would write the server code to take the requests from Angular and then internally reach out to the other API to get the data required. Basically use the node server to act like a proxy to reach the other API.
jfriend00 is right in his comment, this is a question of asynchronous calls.
You are looking for the initial requests to kick off the following: Frontend Request > NodeJS API > Database Query
And the response to fulfill and return promises to create a response chain in the reverse order: Database Response > NodeJS API > Frontend Response
You are probably looking for the angular function $http.get with .then() to perform your frontend calls. But you also need an asynchronous function to request the data from within the API or a database instance, then provide it on an endpoint that the frontend can consume. For that you need a promise or callback in your server-side code as listed in jfriend00's comment.
Consider working on just your NodeJS API until you can achieve the response and requests you need, and build out your frontend with Angular later. The users.js file is a fine endpoint to start on.

Categories

Resources