Why does my angular/express GET work but not POST? - angularjs

Here how my button's set up. The Updates.getUpdates is working. Updates.postAnUpdate returns 404
$scope.postUpdate = function () {
console.log($scope.update);
Updates.postAnUpdate($scope.update);
Updates.getUpdates().then(function (data) {
$scope.updates = data;
});
};
Here is my lovely services
app.factory('Updates', ['$http',
function ($http) {
return {
//Get the current users messages
getUpdates: function () {
return $http({
url: '/updates/',
method: 'get'
}).then(function (result) {
return result.data;
});
},
postAnUpdate: function (update) {
return $http({
url: '/updates/post',
method: 'post',
data: {
update:update,
}
}).then(function (result) {
return result.data;
});
}
};
}]);
Here's my routes to handle the urls
var updates = require('./routes/updates.js');
//Project Updates
app.get('/updates/', updates.getAll);
app.get('/updates/post', updates.newPost);
And finally, here's the code that works with a 200 and console text.
exports.getAll = function (req, res) {
console.log('It worked');
}
So everything should be working for the post too, but it isn't. I'm just trying to do a console command so I know it works and I'm getting a 404
exports.newPost = function (req, res) {
var db = mongo.db,
BSON = mongo.BSON,
newPost = {};
console.log('This is giving me 404 instead of showing up in terminal');
newPost.content = req.body.update;
newPost.author = req.user._id;
newPost.date = new Date();
db.collection('updates').save(newPost, function (err, result) {
if (err) {
throw err;
}
console.log(result);
});
}

Looks as though this is a simple typographic error. in your routes:
app.get('/updates/', updates.getAll);
app.get('/updates/post', updates.newPost);
I think you want
app.post('/updates/post', updates.newPost);

Related

how to get function return value in a variable using angularjs

Here is my code of angularjs file
$scope.httpPost = function (url, json_form_data) {
$http.post(url, json_form_data)
.then(function (response) {
$scope.responseData = response.data;
return $scope.responseData;
}, function (response) {
$scope.content = "Something went wrong";
});
};
Here is the function in which i am calling the above function
$scope.getAuthToken = function (account_type, auth_type, email, type_of_request) { // type of request means login or signUp
var account_type = account_type;
var form_data = {
'email': email,
"auth_type": auth_type,
"account_type": account_type
};
$scope.responseData = $scope.httpPost($scope.authTokenUrl, form_data);
console.log("value of res");
console.log($scope.responseData);
};
The output of the above code is
value of res
loginAndSignup.js:138 undefined
My question is that How can i access that value which function returning because i needed that value.
I tried the following solution
$scope.httpPost = function (url, json_form_data) {
return $http.post(url, json_form_data)
.then(function (response) {
return response;
}, function (response) {
$scope.content = "Something went wrong";
});
};
$scope.login = function (email, auth_token, auth_type, account_type) {
var password = $scope.password;
var form_data = {
//form data
};
var url = $scope.loginUrl;
$scope.httpPost(url, form_data)
.then(function (response) {
return response;
}, function (response) {
$scope.content = "Something went wrong";
});
using $q (A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.)
click here for more detail
used this function
$scope.httpPost = function (url, json_form_data) {
var d = $q.defer();
$http.post(url, json_form_data)
.then(function (response) {
d.resolve(response);
}, function (response) {
d.reject(response);
});
return d.promise;
};

400 bad request on post

Trying to send a request from my factory to the back end, getting the following error: POST http://localhost:8000/messages/58d4b22d57f49028608f7bf9 400 (Bad Request)
Factory:
app.factory('usersFactory', function ($http) {
var factory = {};
var current_user = [];
factory.login = function (data, callback) {
$http.post('/users/', data)
.then(function (response) {
current_user.push(response.data);
callback(current_user);
})
};
factory.getUser = function (callback) {
callback(current_user);
}
factory.destroy = function (callback) {
current_user = [];
callback();
}
factory.writePost = function (data) {
console.log(data);
console.log(current_user[0]._id)
$http.post('/messages/' + current_user[0]._id, data)
.then(function (response) {
$location.url('/wall');
})
}
return factory;
});
Server routes:
var wall = require('./../controllers/serverController.js')
module.exports = function(app){
app.post('/users/', function (request, response) {
wall.login(request, response);
});
app.post('/messsage/:id', function (request, response) {
wall.writeMessage(request, response);
})
}
Sever controller:
module.exports =
{
writeMessage: function (request, response) {
User.findOne({ _id: request.params.id }, function (err, user) {
var message = new Message({ message: request.body, _user: request.params.id });
message.save(function (err) {
user.messages.push(message);
user.save(function (err) {
if (err) {
response.json(err);
}
})
})
})
}
}
this is error of sever side not angular, try to check logs of server.
Also you are using Message , do have schema imported in that ?

GET call to REST API returns null

I am trying to make a GET call to test a REST API but it keeps returning null, is there anything I am doing wrong:
Making the call in controller.js
function ConsumerSearchCtrl($scope, BusinessCategoryService) {
console.log(BusinessCategoryService);
}
127.0.0.1:8000/api/category/ works perfectly fine
Code in services.js for API
/**
*
*/
function BusinessCategoryService(WenzeyAPI, $q) {
var scope = this;
scope.categories = categories;
function categories() {
var q = $q.defer();
WenzeyAPI.get('http://127.0.0.1:8000/api/category/').then(function success (res) {
q.resolve(res.data);
}, function failure (err) {
q.reject(err);
})
return q.promise;
}
}
/**
*
*/
function WenzeyAPI() {
var scope = this,
ip = "http://127.0.0.1:8000";
scope.get = get;
scope.post = post;
function get(url, data) {
data = data || {};
var req = {
method: 'GET',
url: url,
data: data
}
var q = $q.defer();
$http(req).then(function success(response) {
q.resolve(response);
}, function failure(err) {
q.reject(err);
});
return q.promise;
}
function post(url, data) {
data = data || {};
var req = {
method: 'POST',
url: url,
data: data
}
var q = $q.defer();
$http(req).then(function success(response) {
q.resolve(response);
}, function failure(err) {
q.reject(err);
});
return q.promise;
}
}
Removing WenzeyAPI and using $http resolved it.
function BusinessCategoryService($http) {
this.getAllData = function () {
return $http({
method: 'GET',
url: 'http://127.0.0.1:8000/api/category/',
});
}
}

Async Controller Action Method invoke by using AngularJS

I am new to AngularJS, I want to know how to call an Async Controller Action Method in MVC by angularJS. I already tried with below code. Can someone help me in this. Here is my AngularJS code
$scope.updateEmp = function () {
var response = $http({
method: "post",
url: "/Home/UpdateCustomer",
data: JSON.stringify($scope.Customer),
dataType: "json"
}).success(function () {
$scope.cancel();
toaster.pop('success', "Success", 'Updates Successfully...!!');
// showAlert("alert-success", "Updated!");
}).error(function () {
toaster.pop('error', "Error", 'Error while getting data', null, 'trustedHtml');
// alert("Error while getting data");
});
// return response;
}
My Action Method is below
[HttpPost]
public async void UpdateCustomer(Customer Upcustomer )
{
await System.Threading.Tasks.Task.Run(() =>
{
using (BusinessEntities dbContext = new BusinessEntities())
{
var customer = dbContext.Customers1.First(c => c.CustomerID == Upcustomer.CustomerID);
customer.Fname = Upcustomer.Fname;
customer.Lname = Upcustomer.Lname;
customer.Age = Upcustomer.Age;
customer.Adderss = Upcustomer.Adderss;
customer.ContactNo = Upcustomer.ContactNo;
dbContext.SaveChanges();
// return EmptyResult;
// return Json(customers, JsonRequestBehavior.AllowGet);
//return View(customers);
}
});
}
I dont know where your controller method is declared but i suggest it should look like this:
$scope.getAllCustomers = function(){...}
and then in the callback function:
}).success(function () {
$scope.getAllCustomers();
If this is not what you meant, please specify the problem more clearly ^^

angular, node + Service that returns SQL Data as json

Total newbee here. Given this service.js how can I go about returning terms data from sql server
app.service('termsService', function () {
this.getTerms = function () {
return terms
};
var terms = [
{
termid: 11, term: 'Shanika', termDefinition: 'Passmore'
}
];
});
The code below works well on its own so I want to return terms data in the service call above
var sql = require('msnodesql')
, nconf = require('nconf')
,express = require('express');
nconf.env()
.file({ file: 'config.json' });
var connectionString = nconf.get("SQL_CONN");
var app = express();
app.configure(function () {
app.use(express.bodyParser());
});
app.get("/", function(req, res) {
sql.open(connectionString, function(err, conn) {
if(err) {
}
else {
conn.queryRaw("SELECT TOP 10 termid, term, termDefinition FROM Terms", function(err, results) {
if(err) {
}
else {
res.json(results);
}
});
}
});
});
app.listen(3000);
A code for your angular service :
function Service($http) {
var Service = {};
Service.getCriteria = function (criteria,callback) {
$http({
url: "YOUR URL",
params: criteria,
method: "GET",
isArray: true
}).success(callback)
}
return Service;
}
Be aware of that is an async call, so use promises, callback or sync methods.

Resources