I am sending http request and when that request is finished I am trying to go to another state but the problem is it does not goes in the success callback I thought my be I'm getting an error so I wrote the error callback it does not goes in that to. Can anybody tell me what am I doing wrong
$scope.submitUpdatedData= function(user){
debugger;
// $http.post('/url',{params: value}).sucess(function(){
API.updateRecord(user).success(function(res){
$state.go('app' ,{} , {reload: true });
console.log("Hello");
});
}
The API code is given below. Here I invoke the http call
.factory('API', function($http) {
var api = {};
var baseURL = 'http://localhost:3000';
api.addRecord = function(record) {
console.log(record);
// $http.post(baseURL + '/addData', {name: record.name}.);
return $http.post(baseURL + '/addData', {rec:record});
};
api.deleteRecord = function(id){
return $http.get(baseURL +'/delete/' + id );
};
api.updateRecord = function(user){
return $http.post(baseURL + "/update/" ,{rec:user});
};
api.getAllRecord = function(){
return $http.get(baseURL+'/getAll');
};
api.getOneRecord = function(id){
return $http.get(baseURL + '/getOne/' + id)
};
return api;
})
UPDATE
I have replaced the .success part with then but it still not works
Second Update
This is my server side code
var express = require('express');
var mongoose = require('mongoose');
var util = require('util');
var bodyParser = require('body-parser')
var app = express();
var Schema = mongoose.Schema;
require('node-monkey').start({host: "127.0.0.1", port:"50500"});
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
};
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
// app.use(express.json()); // to support JSON-encoded bodies
// app.use(express.urlencoded()); // to support URL-encoded bodies
app.use(allowCrossDomain);
// app.use('/' , require('./index'))
mongoose.connect('mongodb://localhost:27017/myappdatabase');
var userSchema = new Schema({
name: String,
password: String
});
var Todo = mongoose.model('Todo', userSchema);
app.get('/getAll' , function(req, res){
Todo.find({} , function(err , todos){
if (err){
res.send(err);
}
console.log(todos);
res.send(todos);
});
});
app.get('/delete/:name' , function(req , res){
console.log(req.params);
console.log(req.params.name);
Todo.remove({
name : req.params.name
}, function(err, todo) {
if (err)
res.send(err);
// get and return all the todos after you create another
Todo.find(function(err, todos) {
if (err)
res.send(err)
res.json(todos);
});
});
});
app.get('/getOne/:id' , function(req , res){
Todo.find({name : req.params.id}, function(err, todo) {
if (err)
res.send(err);
res.send (todo[0]);
// get and return all the todos after you create another
});
});
app.post('/update', function(req , res){
console.log(req.param('rec').name);
Todo.update({_id:req.param('rec').id} , {$set : {name:req.param('rec').name , password:req.param('rec').password}} , function(err){
if(err)
res.send("Error occured");
res.send("true");
});
});
app.post('/addData' , function(req , res){
console.log( req.param('rec').name);
var p = new Todo({name: req.param('rec').name , password: req.param('rec').password});
p.save(function(err){
if(err){
res.send(err);
console.log(error);
}
res.json(p);
});
});
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);
});
// module.exports = app;
Seems like success and error are deprecated, you should use then instead:
API.updateRecord(user).then(function(res){
$state.go('app' ,{} , {reload: true });
console.log("Hello");
});
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
Source here
Seems like your request is never answered by the API Server. Maybe you can set a timeout for your request. Here it says you can do:
$http.post(url, data, {timeout: 100});
That should timeout your request after 100ms.
Related
I am trying to store result data received from client side into sql database, however I am getting these errors
TypeError: request.query(...).then is not a function
TypeError: callback is not a function
I am quite new to node.js and sql database. I spent quite a bit of time to figure these but not sure where to start,,
I tried to remove .then, it works fine but still throws 2nd error. Can anyone please advice on this problem?
node.js
//Receive from Angular Server
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.all("/*", function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
next();
});
app.listen(1433, function () { console.log('Example app listening on port 1433!') })
var sql = require('mssql');
var config = {
server: "",
database: "",
user: "",
password: "",
port:
};
app.post('/ping', function (req, res) {
res.send(res.body);
var jsondata = JSON.stringify(req.body);
var test = JSON.parse(jsondata);
var values = [];
values.push(test.GradeA, test.GradeB, test.GradeC)
console.log(values);
//values = [ '25', '36', '32' ]
var dbConn = new sql.Connection(config);
dbConn.connect().then(function () {
var transaction = new sql.Transaction(dbConn);
transaction.begin().then(function () {
var request = new sql.Request(transaction);
request.query("INSERT INTO RMS (GradeA, GradeB, GradeC) values VALUES ? ", [values])
.then(function () {
transaction.commit().then(function (recordSet) {
console.log('Rows Affected :' + request.rowsAffected);
dbConn.close();
}).catch(function (err) {
console.log("Error in Transaction Commit" + err);
dbConn.close();
});
}).catch(function (err) {
console.log("Error in Transaction Begin" + err);
dbConn.close();
});
}).catch(function (err) {
console.log(err);
dbConn.close();
});
}).catch(function (err) {
console.log(err);
});
});
request.query("INSERT INTO RMS (GradeA, GradeB, GradeC) values VALUES ? ", [values]) should be the line giving the error. It assumes the second parameter should be function. And when the second parameter is passed it does not return a promise and thus does not have then method.
mssql modules does not seem to support escaping in the way you are trying to do it. It support input method which can be used to inject data into query. From docs:
request
.input('input_parameter', sql.Int, value)
.query('select * from mytable where id = #input_parameter'
I'm trying to authenticate a user based on values entered in a given form. However, after using res.send(), the function at AngularJS controller is not able to correctly redirect user even if the password and username are correct. Am I handling the callbacks correctly?
Controller
<script>
var app = angular.module('myApp', []);
app.controller("loginController", function($scope,$http) {
$scope.sub = function() {
var config = {
headers : {
'Content-Type': 'application/x-www-form-
urlencoded;charset=utf-8;'
}
}
$http.post('/login', { data:{ username: $scope.username,
password: $scope.password} })
.then(function(response){
if(response.state==0){
console.log('Error!');
} else if(response.state==1){
console.log('action on success');
window.location.href = '/views/success.html';}
}).catch(function(error){
console.log('action on error');
});
Authentication
var db = require('../../config');
exports.login = function(req,res){
var username = req.body.data.username;
var password = req.body.data.password;
db.query('SELECT * FROM users WHERE username = ?',[username], function
(error, results, fields){
var result = "0";
if(error) {
console.log('Code 400, Error ocurred');
}
else{
if(results.length>0){
if(results[0].password == password){
console.log('Code 200, login sucessful');
res.json({ state : 1});
}
}
else{
console.log('Code 400, Password or username invalid');
res.json({ state: 0})
}
}
});
}
server.js
var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var db = require('./config');
var app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(express.static(__dirname + '/app'));
require('./app/routes')(app);
app.listen(3000,function(err){
if(err){
console.log(err);
}
else{
console.log("Listening on port 3000");
}
});
Route.js
var auth = require('../app/middleware/authenticateUser');
module.exports = function (app) {
app.get('/',function(req,res){
res.sendFile(__dirname + '/views/index.html');
});
app.post('/login', function(req, res){
auth.login(req,res);
});
}
Thanks in advance!
You need to inject $window in your controller and then in your successful response
$window.location.href = '/views/success.html';
Although using the $window service is considered AngularJS best practice, I don't think this is where the problem is.
Have you tried console.log() the response object of the $http call?
Maybe the problem is because you put if(response.state) instead of if(response.data.state).
I'm learning Nodejs and ExpressJS. I'm trying to use ExpressJS and 2 Node modules (request-ip and geoip2) to get the client IP address for geolocation and then outputting the geolocation in the browser using AngularJS (1.x).
So far for my Nodejs and Expressjs code I have
var express = require('express');
// require request-ip and register it as middleware
var requestIp = require('request-ip');
// to convert the ip into geolocation coords
var geoip2 = require('geoip2');
// Init app
var app = express();
var port = process.env.PORT || 8000;
geoip2.init(); // init the db
//app.use(requestIp.mw({ attributeName: 'myCustomAttributeName'}));
var ip = '207.97.227.239';//67.183.57.64, 207.97.227.239
// respond to homepage req
app.get('/', function (req, res, next) {
//var ip = req.myCustomAttributeName;// use this for live
//var ip = '207.97.227.239';/* use this for testing */
console.log('requestIP is ' + ip);
next();
// geolocation
geoip2.lookupSimple(ip, function(error, result) {
if (error) {
console.log("Error: %s", error);
}
else if (result) {
console.log(result);//ipType was causing console.log duplication, IDK why
}
});
});
// set static folder
app.use('/', express.static(__dirname + '/public'));
app.listen(port, function(){
console.log('user location app is running');
});
And for Angular I have
angular.module('UserLocation', []);
angular.module('UserLocation')
.controller('MainController', MainController);
MainController.$inject = ['$http'];
function MainController($http) {
var vm = this;
vm.result = '';
vm.message = 'Hello World';
vm.getLocation = function() {
console.log();
return $http.get('localhost:8000', {
params: {result: result}
})
.then(function(result){
console.log(result);
})
};
};
vm.result in the Angular controller is for the result from the geoip2 Node module that performs the geolocation.
I can get the result in the console no problem but I'm not to sure how to pass it to Angular. I'm using the $http service but I'm not sure where to go from here...?
How do I pass the result from the geoip2 Node module to my Angular controller with $http?
The problem is that you are calling next before you are even done.
app.get('/', function (req, res, next) {
//next(); this line should be commented
// geolocation
geoip2.lookupSimple(ip, function(error, result) {
if (error)
return res.status(400).json({error: 'Something happened'});
return res.send(result);
});
});
Then on angular
$http({
method: 'GET',
url: '/yourURL'
}).then(function (response) {
console.log(response);
});
If you want to use the user IP to get location:
app.get('/', function (req, res, next) {
//next(); this line should be commented
// geolocation
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
geoip2.lookupSimple(ip, function(error, result) {
if (error)
return res.status(400).json({error: 'Something happened'});
return res.send(result);
});
});
How to change my angular controller and node server code to post data into my database
Controller
var app= angular.module('App',[]);
var PD;
var address=null;
var pid=1;
app.controller("Ctrl",function($scope,$http) {
$http.get('/load').success(function(data) {
$scope.persons= data;
});
$scope.submit=function(){
PD=prompt("Enter person details");
if(PD.localeCompare("")!=0)
{
var data=JSON.stringify({pid:pid,
persondescription:PD,
url:$scope.url,
address:address,
submittedtime:new Date().toLocaleString().replace("/.*(\d{2}:\d{2}:\d{2}).*/", "$1"),
status:'Submitted'
});
console.log(data);
$http.post('/send',data).success(function(data,status) {
console.log(data);
console.log('Data posted successfully');
});
});
Node server code
Server
var express = require('express');
var http=require('http');
var bodyParser= require('body-parser');
var mysql = require('mysql');
var app = express();
app.set('port', 3000);
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }));
enter code herevar connection = mysql.createConnection({
host : '-',
user : '-',
password : '-',
database : '-'
});
connection.connect(function(error){
if(error)
{
console.log("Problem with MySQL"+error);
}
else
{
console.log("Connected with Database");
}
});
app.get('/',function(req,res){
res.sendfile('managementt.html');
});
/*
* Here we will call Database.
* Fetch news from table.
* Return it in JSON.
*/
app.get('/load',function(req,res){
connection.query("SELECT * from personactivity",function(err,rows){
if(err)
{
console.log("Problem with MySQL"+err);
}
else
{
res.end(JSON.stringify(rows));
}
});
});
app.post('/send', function(req,res){
console.log(req.body);
var query = connection.query('insert into personactivity set ?',req.body, function(err, res) {
if (err) {
console.error(err);
return res.send(err);
} else {
return res.send('Ok');
}
});
app.listen(3000,function(){
console.log("It's Started on PORT 3000");
});
How to change my angular controller and node server code to post data into my database
This is my Server.js file (NodeJS):
var express = require('express');
var server= require('http');
var path= require("path");
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app= express();
var staticDIR = path.resolve(__dirname, "./www");``
app.use(express.static(staticDIR));
app.use(bodyParser.json());
app.get("*", function (req, res) {
var indexViewPath = path.resolve(__dirname, "./www/index.html");
res.sendFile(indexViewPath);
});
var dbURI = 'mongodb://localhost:27017/mydatabase';
mongoose.connect(dbURI);
mongoose.connection.on('connected', function () {
console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error',function (err) {
console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
console.log('Mongoose disconnected');
});
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose disconnected through app termination');
process.exit(0);
});
});
var userSchema = new mongoose.Schema({
name: String,
password:String,
email: {type: String, unique:true},
createdOn: { type: Date, default: Date.now }
//modifiedOn: Date,
//lastLogin: Date
});
mongoose.model( 'User', userSchema );
var User = mongoose.model('User');
var CompanySchema = new mongoose.Schema({
CompanyName: String,
password:String,
email: {type: String, unique:true},
createdOn: { type: Date, default: Date.now }
//modifiedOn: Date,
//lastLogin: Date
});
mongoose.model( 'company', userSchema );
var company = mongoose.model('company');
User.find({}, function(err, users) {
if(!err){
console.log(users);
}
});
company.find({}, function(err, users) {
if(!err){
console.log(users);
}
});
app.post('/account', function(req, res){
new company({
CompanyName:req.body.Company,
email:req.body.email,
password:req.body.password
}).save(function(err,doc){
if(err)res.json(err);
else res.send("succesfully inserted");
console.log(res);
});
});
This is my Middleware to get tha data:
app.get('/details', function (req, res) {
console.log('I received a GET request');
company.find({}, function(err, users) {
if(!err){
console.log(users);
}
else{
res.render('/details',{users:docs})
}
});
});
app.listen(9000);
console.log("Server Running on port 3000");
This is my Controller.js (AngularJS) file:
angular.module('myApp', ['ngMaterial','firebase','ui.router'])
.controller('detailsCtrl', function($scope,myfirebaseAddress,$location,$timeout) {
var ref = new Firebase(myfirebaseAddress);
})
This is my route where I want to show the mongoDb saved data
<ui-view>
<div class="sub-header">
<h3>Company Details</h3>
</div>
<ul>
<li ng-repeat="users in user">
{{user.email}}
</li>
</ul>
</ui-view>
Thanks in advance
instead if writing below code
if(!err){
console.log(users);
}
else{
res.render('/details',{users:docs})
}
do like this
if(!err){
res.send(users);
}
else{
res.send('could not retrived data');
}
in controller side you can get your all data inside success call back function.here also check
app.listen(9000);
console.log("Server Running on port 3000");
this should like below.
app.listen(9000);
console.log("Server Running on port 9000");
Controller to get the requested data
.controller('detailsCtrl', function($scope,$http) {
$scope.users = [];
$http.get('/details').then(function(d)
{
console.log(d);
$scope.users= d.data;
},function(err)
{
console.log(err); }
)
})
server route
app.get('/details', function (req, res) {
console.log('I received a GET request');
company.find({}, function(err, users) {
if(!err){
res.json(users);
}
});
});
If you want to retrieve your data, you must stop this:
res.render('/details',{users:docs})
If you want to serve data with an angular app, you have to stop to render a view and start to give back a json in your response.
res.jsonp(users)
Then you've to adjust your controller.
Write a service like:
angular.module('yourApp')
.service('userService', function($http){
return {
getUsers: function(url) {
return $http.get(url)
}
}
})
this should return an http promise.
In your controller you handle this promise this way:
$scope.users = function(){
userService.getUsers('/users')
.then(function(users){
//You have your users object
})
}
remember to handle the unsuccesfull case of your promise
Try to use the angular http module to get the node/express response that get the data from mongodb in client side; like this: https://github.com/J-Alex/api_rest_mvc