database node.js to angularjs - javascript

I am new to Node.JS and AngularJS and I have made a connection to a database using Node.js (code below)
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodetest'
});
connection.connect();
connection.query('SELECT * from testtable', function(err, rows, fields) {
if (!err) {
var test = rows;
console.log('The solution is: ', test);
return test;
} else{
console.log('Error while performing Query.');
}
});
connection.end();
the database consists of 2 tables (ID and name) and only has 1 row (1, 'Luuk')
my code gets put through Grunt for compiling.
when I run the script stated above, it give the expected result (The solution is: [ RowDataPacket { ID: 1, name: 'Luuk' } ])
but when I want to add this to a controller in angularjs, it gives no results
app.controller('NameController', function() {
this.nameList = test;
});
how would be fixed?

I think that you're confusing concepts.
Angular.js and Node.js are running in a COMPLETELY different environment. Node.js is a server, that is running locally in your machine, which you can access via browser with the url localhost:3000 for example. But this server can be running on another machine for example, which you would be able to access via IP, something like 123.4.5.678:3000.
To share data between the backend and the frontend, you must do this over requests. When you access the localhost via browser, you're doing a request to the server, and the server provide some response, like a HTML page or something like that.
Look this example at the Nodejs Docs
http.createServer( function(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(3000);
In the response we are returning a plain text. But this can be json, with your search at the database.
And you can do a specific route, like /getTestTable which you can call in the Angular, with the $http service, and handle this.
I suggest to take a better look at how Node.js works, and Angular.js too.
You would like to take a look too at the Express.js, a framework for Node.

Check the scope of variable test - it is defined inside call back function of connection.query. Try defining variable 'test' globally.

Related

Node.JS - Check result exists before running function

I'm relatively new to Node JS. I'm attempting to query the database, and then simply emit that data to the front end using socket.io, however I've noticed that it is intermittently sending the data / not sending the data to the front end. I'm assuming that the reason behind this is because the query has not yet finished yet, and was wondering how you'd wait for the result to be accessible before continuing?
I'm using npm mysql to access the database within the socket such as below:
var mysql = require('mysql');
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'root',
password : '',
database : 'db'
}
);
Here is my query:
connection.query(queryString, function(err, result, fields){
if(err) throw err;
socket.emit('emitFunction', result);
});
The callback only called after query done so the result should available inside the callback function. Log both err and result to see what happened

Hide an API key (in an environment variable perhaps?) when using Angular

I'm running a small Angular application with a Node/Express backend.
In one of my Angular factories (i.e. on the client side) I make a $http request to Github to return user info. However, a Github-generated key (which is meant to be kept secret) is required to do this.
I know I can't use process.env.XYZ on the client side. I'm wondering how I could keep this api key a secret? Do I have to make the request on the back end instead? If so, how do I transfer the returned Github data to the front end?
Sorry if this seems simplistic but I am a relative novice, so any clear responses with code examples would be much appreciated. Thank you
Unfortunately you have to proxy the request on your backend to keep the key secret. (I am assuming that you need some user data that is unavailable via an unauthenticated request like https://api.github.com/users/rsp?callback=foo because otherwise you wouldn't need to use API keys in the first place - but you didn't say specifically what you need to do so it is just my guess).
What you can do is something like this: In your backend you can add a new route for your frontend just for getting the info. It can do whatever you need - using or not any secret API keys, verify the request, process the response before returning to your client etc.
Example:
var app = require('express')();
app.get('/github-user/:user', function (req, res) {
getUser(req.params.user, function (err, data) {
if (err) res.json({error: "Some error"});
else res.json(data);
});
});
function getUser(user, callback) {
// a stub function that should do something more
if (!user) callback("Error");
else callback(null, {user:user, name:"The user "+user});
}
app.listen(3000, function () {
console.log('Listening on port 3000');
});
In this example you can get the user info at:
http://localhost:3000/github-user/abc
The function getUser should make an actual request to GitHub and before you call it you can change if that is really your frontend that is making the request e.g. by cheching the "Referer" header or other things, validate the input etc.
Now, if you only need a public info then you may be able to use a public JSON-P API like this - an example using jQuery to make things simple:
var user = prompt("User name:");
var req = $.getJSON('https://api.github.com/users/'+user);
req.then(function (data) {
console.log(data);
});
See DEMO

Node.js and SQLite3

I am want to create web server that will return data for my mobile app. I use Node.js for server and SQLite3 for database. I created method that must return data from sql, but I don't know how to do it correctly. As I know all methods from SQLite lib are async so I have no idea how to do sync request for DB. I tried this way:
app.get('/getAllLeagues',function (req, res) {
console.log("get")
var obj = db.all("SELECT name FROM Leagues")
})
But seems that obj is still the same as db object
I'm assuming that your app is an express server instance or similar. The database query function takes a callback function that is called once the queried rows are ready or an error is found.
app.get('/getAllLeagues',function (req, res) {
console.log("get")
var obj = db.all("SELECT name FROM Leagues",
function(err, rows) {
res.type('json');
res.send(rows);
});
});
For simplicity, there is no error handling. It is better to try..catch a similar request to avoid crashing your app in case the database or the table is not found.

NodeJS and MySQL Getting 500 error after first query

I have declared mysql, and my connection in app.js like so:
var mysql = require('mysql');
var connection = mysql.createConnection({
host: '192.168.1.75',
user: 'dev',
password: 'devaccount',
database: 'PugIt'
});
app.set('connection', connection);
And in my User.js for registration I have:
router.route('/register/steam/finish')
.get(function(req, res) {
res.render('user/register_steam');
})
.post(function(req, res) {
var connection = req.app.get('connection');
connection.connect();
// Look For Users
connection.query("SELECT * FROM Users", function(err, rows, fields) {
console.log('We Found Something!');
});
connection.end();
});
When the page first loads and I hit register, it works fine, but if I hit the button a second time I get a 500 error on my server.
But if I manually declare var connection inside each route file, this does not happen.
How come I cannot use req.app.get with MySQL, I used this method when I used to use MongoDB which worked great that way I had one main config in app.js I could alter to change in all route files if I needed. Not sure why I'm getting a 500 error on second POST
I think the connection.connect() and connection.end() on every POST request is causing problems. Drop those two lines and you should be good to go. This way the connection is only established once and all requests can re-use the same connection without constantly trying to tear it down and bring it back up again.
You can also create a pool of mysql connections if you find yourself needing greater concurrency with your database queries.

Adobe Brackets Live Preview can't reach Node.js server

I'm having trouble running a Node.js server with Adobe Brackets. Once in live preview (the URL is http://localhost:SOMERANDOMPORT/path/to/file.html), I start the server. If I type http://localhost:3000/test straight into another tab, it displays the correct JSON.
I then added an event function to an element in file.html that upon clicking it makes an AJAX request to my server and uses the response to change some of its inner HTML. However, clicking the element in live preview fails, and the error callback gets called instead.
How can I fix this? I suspect it has to do with the fact that the AJAX request sends to http://localhost:SOMERANDOMPORT/test rather than http://localhost:3000/test, but I can't seem to find a solution.
Everything runs locally. Below is my server:
var express = require('express');
var mysql = require('mysql');
var app = express();
app.get('/test', function(req, res){
var connection = mysql.createConnection(...);
connection.query("SELECT author FROM posts", function(err, results) {
if (err) {
console.log(err);
console.log('Error on retrieving data.');
res.send(err);
return;
}
console.log(results[results.length - 1]);
res.send(results[results.length - 1]); // return last row
});
connection.end();
});
app.listen(3000);
console.log('Listening on port ' + port);
And the event function:
function getAuthor() {
$.ajax({
type: 'GET',
url: '/test',,
success: function(data, status) {
$('.author').text('Authored by ' + data.author);
},
error: function(jqXHR, status, error) { // this always get called
$('.author').text('Something went wrong.');
}
});
}
I appreciate any help.
The simplest fix is to point Live Preview directly at your own Node server, letting it serve up the pages itself from the correct port number (rather than serving the pages from Brackets's built-in server that's on a different port). See instructions on the Brackets wiki under "Using your own backend."
The downside is that HTML live updating is disabled - but you'll still get CSS live updating, and Brackets falls back on a simpler "live reload" on save for HTML content.
To keep live HTML updating enabled you'd need to work around the port number difference somehow. You could hardcode a localhost:3000 base URL for testing, but you'll run same-origin problems due to the port numbers not matching. Working around that would be pretty involved (set up CORS on your Node server, etc.).
One other option for keeping the full Live Preview experience is to shim all your $.ajax() calls so they return hardcoded dummy data without hitting the server. If you're already doing some mocking for unit tests, you might be able to reuse that existing infrastructure for this.

Categories