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 ?
Related
Upgrade to angularjs version 1.7 and this code does not compile
app.factory('LoginService', function ($http) {
return {
login: function (param, callback) {
$http.post(url, param)
.success(callback)
.error(function (data, status, headers, config) {
});
}
};
});
On the controller I make the call to the service LoginService
function LoginController($http, $location, LoginService, blockUI) {
var vm = this;
LoginService.usuario(
{login: vm.username, clave: vm.password},
function (data, status, headers, config) {
vm.resultado = data;
if (vm.resultado == "True") {
window.location = "/Home/Index";
} else {
vm.error = 'Usuario o password incorrecto';
}
});
};
I want to know how the function is called from the controller because it implemented the http.post service using .then
app.factory('LoginService', function ($http) {
return {
login: function (data) {
$http.post(url, data)
.then(function (resultado) {
debugger;
if (resultado.data === "True") {
return resultado.data;}
else {
console.log("NO");}
});
}};
});
I suggest you get familiar with a AngularJS $q service and its Promise API.
You LoginService.login(...) method should return the Promise from $http.post(...):
app.factory('LoginService', function ($http) {
return {
login: function (data) {
return $http.post(url, data)
.then(function(response) {
return response.data;
});
});
Then, your Controller can access the returned data via the resolved Promise:
function LoginController(LoginService) {
var vm = this;
LoginService.login({login: vm.username, clave: vm.password})
.then(function (result) {
// handle result here...
});
the solution would be this:
function LoginController($scope,$window,$q,LoginService) {
$scope.fnBusqueda = function () {
var promesas = [
obtenerLogin()
];
$q.all(promesas).then(function (promesasRes) {
var oArrayResponse = promesasRes;
if ((oArrayResponse.length > 0)) {
$scope.respuesta = oArrayResponse[0];
if ($scope.respuesta == "True") {
window.location = "/Home/Index";
} else {
$cope.error = 'Usuario o password incorrecto';
}
}
});
};
function obtenerLogin() {
var defered = $q.defer();
var promise = defered.promise;
LoginService.login(url_valida_login, '{login:X,clave:X}').then(function (response) {
defered.resolve(response);
}).catch(function (data) {
defered.resolve([]);
})
return promise;
}
}
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;
};
I am using angular and talking to an express backend. I can retrieve data from my .get, but my .post is generating a validation error
Client-controller:
$scope.addFriend = function()
{
friendsFactory.addFriend($scope.newFriend, function (data)
{
$location.url('/friends' + data._id);
});
}
Client-factory:
factory.addFriend = function (newFriendData, callback) {
$http.post('/friends', newFriendData)
.then(function(response)
{
console.log(response.data);
//callback(response.data);
})
}
Server-route:
app.post('/friends', function (request, response) {
console.log('routes')
friends.create(request, response);
})
Server-controller:
create: function(request, response)
{
console.log('request');
var friendInstance = new Friend();
friendInstance.first_name = request.params.fname;
friendInstance.last_name = request.params.lname;
friendInstance.b_day = request.params.bday;
friendInstance.save(function(err,data)
{
if (err)
{
response.json(err);
}
else {
rewponse.json(data);
}
})
Error on console:
Object {errors: Object, message: "Friend validation failed", name: "ValidationError"}
this is most likely a mongoose error, the document that you're trying to persist does not follow the Friend schema.
id i m getting in the controller but its nt coming in the server,when i am clicking on delete i am getting the id in console. its showing error "possibly unhandled rejection" and error 404
this is my server:-
var express=require('express');
var mongojs=require('mongojs');
var bodyParser=require('body-parser');
var app=express();
var db=mongojs('contactlist',['contactlist']);
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.get('/Contactlist',function (req,res) {
console.log("ireceived a get request")
db.contactlist.find(function (err,docs) {
console.log(docs);
res.json(docs);
})
})
app.post('/Contactlist',function (req,res) {
db.contactlist.insert(req.body,function (err,doc) {
res.json(doc);
console.log(doc);
})
})
app.delete('/contactlist/:id',function (req,res) {
var id= req.params.id;
console.log(id);
})
app.listen(3000);
console.log('Server running on port 3000');
this is my controller
var ContactListApp = angular.module('ContactListApp',[]);
ContactListApp.controller('AppCtrl',[ '$scope','$http',function($scope,$http) {
console.log("controller");
var refresh=function () {
$http.get('/Contactlist').then(success,error)
function success(response) {
console.log(response,"I got the data i requested")
$scope.Contactlist=response.data;
}
function error(response){
alert("Please check your code");
}
};
refresh();
$scope.addContact=function () {
console.log($scope.contact);
$http.post('/Contactlist',$scope.contact).then(success,error)
function success(response) {
console.log(response);
$scope.Contactlist=response.data;
refresh();
};
function error() {
alert('error occured');
}
$scope.contact =null;
}
$scope.remove=function (id) {
console.log(id);
$http.delete('/contactlist/',id);
refresh();
}
}]);
I think you should try calling it like this
$http.delete('/contactlist/'+id);
if you are getting ID here
var id= req.params.id;
console.log(id);
then simply run query
db.contactlist.remove({_id:id},function (err,doc) {
if(err){ console.log("err n remove")}
else{console.log("Remove Success")}
})
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);