I can't get my get request to work - html

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);
});
}
}
}]);

Related

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>

Unknown provider: callbackProvider <- callback

I am stuck with this code for very long time and apply all the patches available on net but didn't find the effective one.It is still giving error while calling service from controller.
Here the code below
<HTML ng-app="myApp">
<body ng-controller = "myCtrl">
<div>{{me}}</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script>
var app = angular.module('myApp',[])
app.controller('myCtrl',function($scope,myService){
myService.getx(function(data){
console.log(data);
$scope.me = "data";
});
});
</script>
<script>
app.service('myService',function($http,callback){
this.getx= function(){
return $http({
method: "GET",
url: "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"
}).then(function (response) {
console.log(response)
return callback(response);
}, function (error) {
throw error;
console.log("Error",error)
});
}
});
</script>
</HTML>
i'd rewrite it like this:
APP CTRL:
var app = angular.module('myApp',[])
app.controller('myCtrl',function($scope,myService){
myService.getx()
.then(
function(data){ //handle the $http promise here
console.log(data);
$scope.me = "data";
},
function(err){
console.log('error:' + err);
});
});
SERVICE:
app.service('myService',function($http){
return {
getx: function() {
return $http({ //the $http returns a promise
method: "GET",
url:"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"
});
}
}
});

Data not getting saved in the MongoDB from node.js

I want to create the rest api using node.js and mongodb
I am entering all the details and trying it to store it in the mongodb database.
// call the packages we need
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var morgan = require('morgan');
// configure app
app.use(morgan('dev')); // log requests to the console
// configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
var mongoose = require('mongoose');
// mongoose.connect('mongodb://node:node#novus.modulusmongo.net:27017/Iganiq8o'); // connect to our database
mongoose.connect('mongodb://localhost:27017');
var Bear = require('./app/models/bear');
// create our router
var router = express.Router();
// middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next();
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// on routes that end in /bears
// ----------------------------------------------------
router.route('/bears')
// create a bear (accessed at POST http://localhost:8080/bears)
.post(function(req, res) {
var bear = new Bear(); // create a new instance of the Bear model
bear.name = req.body.name; // set the bears name (comes from the request)
bear.email= req.body.email; // set the bears email(comes from the request)
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear created!' });
});
})
// get all the bears (accessed at GET http://localhost:8080/api/bears)
.get(function(req, res) {
Bear.find(function(err, bears) {
if (err)
res.send(err);
res.json(bears);
});
});
// on routes that end in /bears/:bear_id
// ----------------------------------------------------
router.route('/bears/:bear_id')
// get the bear with that id
.get(function(req, res) {
Bear.findById(req.params.bear_id, function(err, bear) {
if (err)
res.send(err);
res.json(bear);
});
})
// update the bear with this id
.put(function(req, res) {
Bear.findById(req.params.bear_id, function(err, bear) {
if (err)
res.send(err);
bear.name = req.body.name;
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear updated!' });
});
});
})
// delete the bear with this id
.delete(function(req, res) {
Bear.remove({
_id: req.params.bear_id
}, function(err, bear) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
// REGISTER OUR ROUTES -------------------------------
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
The Model is given below:-
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String,
email: String
});
module.exports = mongoose.model('Bear', BearSchema);
I am trying it to save the name and the email in the mongodb database but only _id is created instead of name, email.
Here is the result:-
[
{
"_id": "567f1f92db24304013000001",
"__v": 0
},
{
"_id": "567f2765db24304013000002",
"__v": 0
}
]
Can anybody tell me why the data are not getting saved in the database.
Please kindly help.
Thanks in Advance.
I think your POST request is not good, so I made this simple script to check it out:
var XHR = (function() {
var _xhr = (function() {
try {
return new(this.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
} catch (e) {}
})();
return function(method, url, params, callback) {
_xhr.onreadystatechange = function() {
if (_xhr.readyState == 4) {
var _response;
try {
_response = JSON.parse(_xhr.response);
} catch (e) {
_response = _xhr.responseText;
}
if (_xhr.status != 200) {
// catch an error
console.error('error', response);
} else {
if (callback) {
callback(_response);
} else {
// deal with it
}
}
}
}
if (!params) {
params = JSON.stringify({});
} else {
params = JSON.stringify(params);
}
_xhr.open(method, url, true);
// just json in this case
_xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");
_xhr.send(params);
};
})();
fire it up in browser's console, like this
XHR('POST','api/bears', { name:'yogi', email:'yogi#bears.com'}, function(){ console.log(arguments) });
and your record will be saved.
{ "_id" : ObjectId("567e875d068748ee5effb6e0"), "email" : "yogi#bears.com" "name" : "yogi", "__v" : 0 }
Long story short - your code is okay, your POST is not.

NodeJS: saving JSON to MongoDB

I am trying to get JSON from an API and store it into a MongoDB database.
Obviously, it doesn't work. My app seems to hang around the point where I try to save the data to the database. Please advise what to do.
Here's my code:
var express = require('express');
var router = express.Router();
var http = require('http');
var mongo = require('mongoskin');
var db = mongo.db("mongodb://localhost:27017/zak", {native_parser : true});
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
var site = 'http://www.vsechnyzakazky.cz/api/v1/zakazka/?format=json&limit=2';
function getData(cb) {
http.get(site, function(res) {
// explicitly treat incoming data as utf8 (avoids issues with multi-byte chars)
res.setEncoding('utf8');
// incrementally capture the incoming response body
var body = '';
res.on('data', function(d) {
body += d;
});
// do whatever we want with the response once it's done
res.on('end', function() {
try {
var parsed = JSON.parse(body);
} catch (err) {
console.error('Unable to parse response as JSON', err);
return cb(err);
}
// pass the relevant data back to the callback
cb(
parsed.objects
);
});
}).on('error', function(err) {
// handle errors with the request itself
console.error('Error with the request:', err.message);
cb(err);
});
}
function writeData (data, allGood){
// couple of visual checks if all looking good before writing to db
console.log('writing');
console.log(typeof data);
console.log(data);
db.collection('zakazky').save(data, function(error, record){
if (error) throw error;
console.log("data saved");
});
}
function allGood(){console.log('all done');}
getData(writeData);
// ---------------------
module.exports = router;
You are calling the save() instead of insert(). Change this part and it will work:
// this should call insert, not save
db.collection('zakazky').insert(data, function(error, record){
if (error) throw error;
console.log("data saved");
});

Angularjs + nodejs + 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;
})
}