I'm trying to make a POST request from Angular Factory to Node.
Angular Factory -
function saveUser(userObject){
var createUser = $http({
method: 'POST',
url: 'CreateUser',
data: userObject,
headers: {'Content-Type': 'application/json'}
});
return createUser.then(callSuccess, callError);
}
Node-
function create(){
app.post('/CreateUser', urlEncodedParser, function(request, response){
var userData = {
firstName : request.body.firstName,
lastName : request.body.lastName,
email : request.body.email,
password : request.body.password,
role : request.body.role
};
console.log(request);
console.log(userData);
dbOpperations.saveData(userData, 'UserTable');
});
}
The call is made but I get response.body = {}
You are getting an empty response because you are not returning anything from node.
please use response.send()
response.send('success')
Thanks all for your help.
I'm able to POST the data and save on db.
I missed to use app.use(bodyParser.json());
Related
trying to call data through openweathermap api
if I call it through 'GET'method.there is
405 (Method Not Allowed)
var req = {
method: 'GET',
url: 'http://api.openweathermap.org/data/2.5/forecast/daily?APPID=' + ApiKey + '&q=London,us',
headers: {
'x-api-key': ApiKey
}
}
$http(req)
.then(function (data) {
console.log(data);
}, function (err) {
console.log(err);
});
#faisal
I ran into this error today, and after some debugging, I realized that it was because I had $httpProvider.defaults.headers.common['X-Requested-With'] = 'HttpRequest'; in my config file. I just disabled CORS for convenience and solved the problem.
This answer is what helped me: Disable CORS in angularJS
Use the params property to encode the search parameters:
var req = {
method: 'GET',
//url: 'http://api.openweathermap.org/data/2.5/forecast/daily?APPID=' + ApiKey + '&q=London,us',
url: 'http://api.openweathermap.org/data/2.5/forecast/daily',
params: { appid: ApiKey, q: 'London,us' }
}
The problem is likely that the &q=London,us is illegal. The comma character needs to be percent-encoded to q=London%2Cus. Use the params property to properly encode the parameters.
Update
I tested it with my APPID (which I am not going to publish) and it worked.
Here is my DEMO on PLNKR with the APPID removed.
I'm trying to make a PUT request to a SQL database through node.js using AngularJS. I keep getting a 400 bad request error. Not sure what's wrong with the request, since this format works using a straight $.ajax call. Any help would be appreciated
vm.approveUser = function(user_id){
console.log('in approveUser');
console.log('user_id', user_id);
$http({
method: 'PUT',
url: '/admin/approve',
data: user_id
}).then(function(){
console.log('back from the /approve');
vm.getRequests();
}); //end .then function
}; //end approveUser
Try simplifying the request and add a return statement. See if it resolves.
vm.approve = function(user_id) {
var url = '/admin/approve';
return $http.put(url, user_id)
.then(function(resp) {
vm.getRequests();
})
.catch(function(error) {
})
.finally(function() {
});
};
I am new to angularjs am tying to learn it but some problems faced me, actually they are two problems:
First Problem: $http.post never works as there is no action and there is no response. However, $http.get is able to work.
Second Problem: Because of the first problem I call my restful webservice by $http.get, but the web service response status always is -1. Though the web service is able to do its work successfully and always response data null, can any one help me.
this my angular part:
var app = angular.module('myLogin',[]);
app.controller('loginController',function($scope,$http){
$scope.login=function(){
var username = $scope.username;
var password = $scope.pass;
$http.get("http://localhost:8080/spring/webservice/login/"+username+"/"+password)
.success(function(data,status){
alert("data : "+data);
alert("Data Inserted Successfully");
window.location.href = "chatScreen.html";
})
.error(function(data,status){
alert("Status: "+status);
window.location.href = "login.html";
});
}
});
and this my web service:
/**
* web service part
*/
#RequestMapping(value="webservice/login/{name}/{pass}", method=RequestMethod.GET)
#ResponseStatus(value = HttpStatus.OK)
public ResponseEntity<String> weblogin(#PathVariable("name") String name, #PathVariable("pass") String pass)
{
System.out.print("username : "+name);
System.out.print(pass);
UserService service = new UserService();
List<UserBean> users = service.getUsers();
if(users!=null)
{
for(UserBean user : users)
if( ( user.getUsername().equals(name) ) && ( user.getPassword().equals(pass) ) )
{
System.out.print("success");
username = name;
//model.addAttribute("result", "Welcome to chat..");
MessageService messageService = new MessageService();
List<MessageBean> messages = messageService.getMessage(username);
String userMessages="";
if(messages != null)
{
for(MessageBean msg : messages)
userMessages +="\n"+msg.getSender() + ": " + msg.getMessage()+" \n";
}
else
userMessages +="You have no Messages !";
//model.addAttribute("whoSendToMe", userMessages);
return new ResponseEntity(HttpStatus.OK);
}
}
return new ResponseEntity<String>("faild", HttpStatus.NOT_FOUND);
}
refer this may be this will give you idea how to approach your problem:-
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this is asynchronous call back
// you will get your data here comming from rest
}, function errorCallback(response) {
// called asynchronously if an error occurs
});
share your code so we will try to solve it
If you use method GET and you receive a -1 returned, it means normally that you are giving a wrong URL.
As for then POST method you should use this syntax:
return $http({
method: 'POST',
url: 'index.php/email/createDeliverable',
data: $.param({
csrfTokenName: --your token--,
userName: user.name,
password: password
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
Remember to add the headers part.
Your server may need a CSRF token validation, in this case you need to pass it, see un my example: csrfTokenName: --your token--,
right now my situation is that I have a post request from an Angular module trying to send some data to an URL handled with node.js and Express.
tickets.js:
$http(
{
method: "post",
url: "/ticketDetail",
headers: {"application/json"},
data: {detail : "test"}
}).then(function successCallback(response)
{
$scope.detail = response.data;
}, function errorCallback(response){});
app.js:
app.post("/ticketDetail", function(req, res)
{
console.log(req.data.detail);
res.json(req.data);
}
It looks like req.data is undefined.
How am I supposed to retrieve the data from my request in my URL handler?
You need to get the data from the body of the req
var qs = require('qs');
app.post('/', function(req,res){
var body = qs.parse(req.body);
var detail = body.detail;
console.log('details',detail); //prints test
});
I believe your post doesn't match the AngularJs syntax. Your $http.post should be like ;
$http.post('/ticketDetail', data, config).then(successCallback, errorCallback);
So for some reason, in your URL handler you are not supposed to access the field data: {detail : "test"} with req.data but with req.body.
app.post("/ticketDetail", function(req, res)
{
console.log(req.body.detail); // prints "test"
res.json(req.data);
}
I'm trying to send HTTP request using the following code:
var editCompanyUrl = 'http://X.X.X.X:YYYY/editCompany';
var userId = localStorage.getItem("UserId");
var token = localStorage.getItem("Token");
var companyId = localStorage.getItem("companyId");
return $http({
method: 'POST',
url: editCompanyUrl,
params: {
token: token,
userId: userId,
companyId: companyId,
companyName: $scope.companyName,
},
timeout: 500
}).then(function (data) {
console.log(data);
//Store Company ID which is used for saving purposes
//localStorage.setItem("companyId", data.data.Company.id);
return data.data.Company;
}, function (data) {
console.log(data);
})
and handler of the request on the server side accepts requests with Content-Type: multipart/form-data. How can I add this content type to the request? I've tried many advices and tips from tutorials but no success. Could you please help me? In addition to it - what should I do when I will add a file with an image to this request? Can I just add it as additional parameter of the request?
Thank you very much!
Angular POST must be like below code.
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
it should have data:{ }
so try to put your params: inside the data and it should work.