Angularjs + nodejs + mysql - mysql

having problem in mobile view no data receive in angularjs..
desktop view is working great.. what's the best solution for this
sorry not good in english.........................................
..................................................................
PHP file
<body ng-app="app" ng-controller="fcontrol">
<div ng-repeat="person in people">
{{person.fname}}
{{person.lname}}
{{person.email}}
{{person.address}}
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
<script src="js/control.js"></script>
</body>
Angularjs(control.js)
angular.module("app" , []);
function fcontrol($scope, $http) {
$http.get("http://localhost:8000/users")
.success(function(data) {
$scope.people = data;
})
}
Nodejs
app.get('/users', function(req, res) {
var s = 'SELECT * FROM tbl_user order by fname';
dbconn.query(s, function(err, rows, fields) {
var row = [];
if (err) throw err;
//console.log(rows)
res.send(rows);
res.end();
});
});

Try chaging your http get url in angular JS code to YOUR IP:8000/users.(Replace localhost with your system IP).
Also make sure your mobile and PC should connected to same network.(If your IP is not public)
Angularjs(control.js)
angular.module("app" , []);
function fcontrol($scope, $http) {
$http.get("http://<your ip>:8000/users")
.success(function(data) {
$scope.people = data;
})
}

Related

Create Web server using Node js model MVC

I'm trying to create a web server, and I'm using to MVC model so I tried to use routes inside so I don't know how can I do this. in the console log thats return all data otherwise in postman I test it it doesn't works. here is my code.
AirModel.js :
AirMonitoring.getAllData = (result) =>{
db.query('SELECT * FROM AirMonitoring', (err, res)=>{
if(err){
console.log('Error while fetching airMonitoring', err);
result(null,err);
}else{
console.log('AirMonitoring fetched successfully');
result(null,res);
}
})
}
airController.js :
exports.getAllData = (req, res)=> {
AirModel.getAllData((err, airMonitoring) =>{
if(err)
res.send(err);
console.log('data', airMonitoring);
res.send(airMonitoring)
})
}
index.js :
const server = http.createServer(function(req, res) {
console.log("http was created!");
if(req.url == '/airMonitoring'){
res.writeHead(200, { 'Content-Type': 'application/json' });
// get latest record of airMonitoring
router.get('/airMonitoring', airController.getAllData);
res.end();
}
});
It's not very clear what router is but I'm assuming it's an express router, and that's not how routing works. Currently you are (re?)defining the route on each request. The routing page is a good place to start, but basically you need to define the routes once.
var express = require('express')
var app = express()
app.get('/airMonitoring', airController.getAllData);
app.listen(PORT, () => {
console.log(`Example app listening at http://localhost:${PORT}`)
})
And also in your AirModel.js you have an error as far as I can tell, when handling the database error you should provide it as first argument, not second:
result(null,err); /* has to be result(err, null) */

Send MySql result in res.send

I'm kind of newbie to the node.js, this might be silly one but not actually getting proper way to achieve this. here I'm trying to send the mysql result from the node.js res.send() method, here below I'm adding my code.
router.post('/get_doc_msgs', (req, res)=>{
var d_msg = "SELECT * FROM msgs WHERE d_id = ?";
var d_msgs = [req.body.doc_id_msgs];
db.query(d_msg, d_msgs, (err,rows) => {
if(err){
console.log('error ', err);
}
else{
res.send(rows)
}
});
})
and here is my function to get the data to the rendered ejs file.
function getmsgs(){
$.ajax({
type:'POST',
url: '/get_doc_msgs',
data: {
doc_id_msgs : $('#doct_id').val();
},
success: function(data){
$('#msg_q').html(data);
}
})
}
advance thank you for help and suggestions .
Here's a complete example of how this might work, I've added server and client code.
If you run
node app.js
Then go to http://localhost:3000 you should see the example working.
The main issue I believe is you need to use a body-parser in Express so you can parse uploaded data correctly. In this case I've used JSON, you could use another encoding if you wished.
The only change I made to the server code was really to add the body parser.
On the client side, I set a content-type header and used JSON.stringify() on the uploaded data.
It's not a silly question, getting all this stuff to play nice takes a little bit of practice and effort!
app.js
const mysql = require('mysql');
const express = require('express');
const app = express();
const router = app;
const port = 3000;
const bodyParser = require("body-parser");
// Add the credentials to access your database
var db = mysql.createConnection({
host : 'localhost',
user : '<user>', /* replace these with real values. */
password : '<pw>', /* replace these with real values. */
database : '<db>' /* replace these with real values. */
});
app.use(bodyParser.json());
app.use(express.static("./"));
router.post('/get_doc_msgs', (req, res)=>{
var d_msg = "SELECT * FROM msgs WHERE d_id = ?";
var d_msgs = [req.body.doc_id_msgs];
db.query(d_msg, d_msgs, (err,rows) => {
if(err){
console.log('error ', err);
} else {
res.send(rows)
}
});
})
app.listen(port);
index.html
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
</head>
<body style="padding:20px">
<label>Doc id:</label><input id="doct_id" value="1"/>
<h4>Response:</h4>
<p id="msg_q"></p>
<script>
function getmsgs() {
$.ajax({
type: 'POST',
url: '/get_doc_msgs',
contentType: "application/json",
data: JSON.stringify({
doc_id_msgs : $('#doct_id').val()
}),
dataType: "json",
success: function(data) {
for(row of data) {
$('#msg_q').append("<li>" + Object.values(row).join("\t") + "</li>");
}
}
})
}
console.log("Doc id:", $('#doct_id').val());
getmsgs();
</script>
</body>
</html>
`getDocMessg = (req, res, next) => {
mess_id = req.body.doc_id_msgs
db.execute("SELECT* FROM msgs WHERE d_id = ?", [mess_id]).then((results) => {
res to render the page you want to send the data to
res.render('name of page', {
message : results[0]
})
})
}`
something like that should do the job you need to adapt it to your website structure, using ejs you can call the variable message and show it on your page :)

NodeJS retrieve JSON and serve to EJS template

my purpose is to get a JSON and serve it to an EJS file.
This is my code:
//server.js
users = require('./controllers/users.js');
global.app_root = path.resolve(__dirname);
app.get('/users', function(req, res) {
res.render('partials/users', {
data: users.retrieve_users
});
})
//users.js
var fs = require("fs");
exports.retrieve_users = function (req, res) {
fs.readFile(app_root + "/config/" + "users-list.json", 'utf8', function (err, data) {
res.end(data);
});
}
//users.ejs
<body>
<%= data %>
</body>
But as output of this code inside the body I see literally this string:
'function (req, res) {
fs.readFile(app_root + "/config/" + "users-list.json", 'utf8', function (err, data) {
res.end(data);
});
}'
The problem is that your data is coming asynchronous and you don't wait for them before the rendering. In fact right now you dont even run the users.retrieve_users function, you just getting back the function declaration and express renders it as string! Change your code to this.
//server.js
users = require('./controllers/users.js');
global.app_root = path.resolve(__dirname);
app.get('/users', function(req, res) {
//a method that get thr user-list data and renders it
users.retrieve_users()
.then(function(users){
res.render('partials/users', {
data: users
});
})
.catch(function(err){
res.status(500).send({ error: 'something blew up' });
})
})
//users.js
var fs = require("fs");
exports.retrieve_users = function () {
//function that returns user-list in promise
return new Promise(function(resolve,reject){
fs.readFile(app_root + "/config/" + "users-list.json", 'utf8', function (err, data) {
if(err) return reject(err)
resolve(data);
});
})
}
//users.ejs
<body>
<%= data %>
</body>

I can't get my get request to work

i can't get my get request to work, im using angular and im new to it and using it because my project dictates i must use it, im trying to get my entry from my mongodb batabase, im also running an expressjs server ill attach all the code i can please tell me of my mistakes i'm sure there are plenty.
//factory
app.factory('whipmeet', ['$http', function($http) {
return $http.get('http://mongodb://127.0.0.1:27017/finalwhipmeet')
.success(function(data) {
return JSON.parse(data);
})
.error(function(err) {
return err;
});
}]);
//controller
app.controller('MainController', ['$scope', 'whipmeet', function($scope, whipmeet) {
whipmeet.success(function(data) {
$scope.meetinfo = data,
$scope.meetlikes = 23;
});
}]);
//index.html(only view)
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
</head>
<body ng-app="WhipMeetApp">
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
<h1 id="test1"> teting </h1>
<div class="main" ng-controller="MainController">
<div class="container">
<div class="card" ng-repeat="meet in meets">
<meet-info info="likes"></meet-info>
</div>
</div>
</div>
<!-- modules -->
<script src="/javascripts/app.js"></script>
<!-- controllers -->
<script src="/javascripts/controllers/MainController.js"></script>
<!-- services -->
<script src="/javascripts/services/whipmeet.js"></script>
<!-- directives -->
<script src="/javascripts/directives/meetInfo.js"></script>
</body>
</html>
//schema im trying to pull
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MeetSchema = new Schema ({
name: String,
location: String,
car: String,
date: Date,
time: Number,
type: String,
stock: Boolean
});
module.exports = mongoose.model('Meet', MeetSchema);
//error i get in console
angular.js:9734 GET http://mongodb//127.0.0.1:27017/finalwhipmeet net::ERR_NAME_NOT_RESOLVED
​
please tell me if i need to post any more files/code for this to be clear, i am really sorry this may be out of format but im a beginner and i'm trying my best to set this up through tutorials and codeacademy, i just need to be able to display my data and how to create a post in the same format.
i greatly appreciate the help of anyone who wants to help, please don't be harsh on a noob.
//meets.js route
var express = require('express');
var router = express.Router();
var Meet = require('../models/Meet.js');
/* GET /meets listing. */
router.get('/', function(req, res, next) {
Meet.find(function (err, meets) {
if (err) return next(err);
res.json(meets);
});
});
/* POST /meets */
router.post('/', function(req, res, next) {
Meet.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* GET /meets/id */
router.get('/:id', function(req, res, next) {
Meet.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* PUT /meets/:id */
router.put('/:id', function(req, res, next) {
Meet.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* DELETE /meets/:id */
router.delete('/:id', function(req, res, next) {
Meet.findByIdAndRemove(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
module.exports = router;
The example uses callback success and error functions. You can use promises as well.
The angular factory calls express routes, which connects with mongoDB for create, update, delete or get operation and sends the response back to factory. Which passes the result/error to controller.
app.controller('MainController', ['$scope', 'whipmeet', function($scope, whipmeet) {
//get all
whipmeet.getWhipmeet(function(data){
$scope.meetinfo = data;
},
function(err){
console.log(err)
});
//get one
whipmeet.getWhipmeet("id::1234567", function(data){
},
function(err){
console.log(err)
});
//create
whipmeet.createWhipmeet({key: "some value"}, function(data){
},
function(err){
console.log(err)
});
}]);
app.factory('whipmeet', ['$http', function($http) {
return {
createWhipmeet: function (obj, success, error) {
$http.post('/meets/', obj, {}).
then(function (data) {
success(data)
}, function (e) {
error(e);
});
},
getWhipmeets: function (success, error) {
$http.get('/meets/').
then(function (data) {
success(data)
}, function (e) {
error(e);
});
},
getWhipmeet: function (id, success, error) {
$http.get('/meets/'+id).
then(function (data) {
success(data)
}, function (e) {
error(e);
});
}
}
}]);

Display data in html/js file using NodeJs from mysql database

My index.js file is
var express = require('express');
var app = express();
var path = require('path');
var router = express.Router();
var data = require('./data/jsonData');
var createDatabase = require('./data/db');
var careateTable = require('./data/createTable');
var insert = require('./data/insert');
var bodyParser = require('body-parser');
var select = require('./data/select');
app.use(express.static(path.join(__dirname, 'www')));
app.use(express.static(path.join(__dirname, 'form')));
app.use(bodyParser());
app.get('/' , function (req , res) {
res.sendFile(path.join(__dirname + '/www/index.html'));
});
app.get('/data' ,function (req , res) {
res.json(data);
});
app.get('/form' ,function (req , res) {
res.sendFile(path.join(__dirname + '/form/index.html'));
});
app.post('/form' ,function (req , res) {
console.log(req.body.user);
console.log(req.body.password);
insert.insertModule(req.body.user , req.body.password);
res.sendFile(path.join(__dirname + '/www/index.html'));
});
app.get('/show' , function (req , res) {
var i ;
select.select( function (err, results) {
if (err == 'error') {
console.log(err);
} else {
console.log(results);
res.send(results.username);
}
});
});
app.listen(3000);
console.log("App is listning on port 3000");
and select.js is
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "NodeDataBase"
});
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
});
module.exports = {
select: function (callback) {
var sql = "SELECT username , password FROM login ";
con.query(sql, function (err, result , fields) {
if (err) {
callback("error", err)
} else {
callback("success", result)
}
});
}
}
I want to show the results object data to html file , So how can i do this please suggest me.
from a get request /show it will show all userdata fetched from the database
I´ll try to explain the way it works (with the consideration on you are now able to see the data on 'http://localhost:3000/show') . Plz, guys, correct me if I do explain something in the wrong way.
There, what you have in your code, is the
Server side code
mysql: Declares connection to database (this is your database connector)
node.js: Declares methods to put/push/get data from database (your server side as is)
express.js: Declares urls to put/push/get data from database (http/https router)
Then, if we check the code, we can see the declaration of a server api - for example app.get('/show')
There, what you are saying is that express, will use the url /show with the method GET
Here is where your client appears in scene. Now, we suppose your server is up and running, waiting to serve GET petitions on http://localhost:3000/show.
If that is correct, when clicking the link you should see the user names, and now you will need an http client to connect to your http server side.
The way you can grab data on your HTML client from your server, is javascript.
Then, you will need to build an HTML file, that will also contain a javascript script (in my example written in angular).
The HTML (this is written in jade. you can convert it) should look like this:
Client HTML Code
You should create an index.html file, and paste this code
<!doctype html>
<html ng-app>
<head>
<title>My AngularJS App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyCtrl">
<table>
<thead>
<tr>
<th>
<p>Name</p>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td>
<p>{{user}}</p>
</td>
</tr>
</tbody>
</table>
</div>
<script>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope, $http) {
//This method will call your server, with the GET method and the url /show
$http.get("http://localhost:3000/show").then(function(success){
if(success.data.length>0)
{
$scope.users=success.data;
}
});
}
</script>
</body>
</html>
This code should capture the data and show a row in the table for every name in the database.
Hope it helps, at least as a clear explanation of how the full stack (client-server) works.
May be you can use view engine such As EJS, Jade to render data from node to the front end.
If you want to render the data on the html page, i will do it like http://localhost:3000/show : with json -resonponse
var express = require('express');
var app = express();
require('json-response');
app.get('/', function(req, res){
res.ok({foo: 'bar'}, 'hello world');
});
i will return json from the link and in Index.html with the help of jquery/Ajax will hit the link , retrieve the value and show it on HTML