unable to retrieve request param in node js - angularjs

In my angular js factory, i am making an ajax call to transfer the input model value to the server side ( node js) but when i try to retrieve it , i see 'undefined' .
angular js :
angular.module('name-App').factory('myService', function($http,$rootScope) {
return {
getFoos: function(stock) {
console.log("----------->"+stock.toString());//displays the value correctly over here .
//return the promise directly.
return $http({
url:'http://localhost:3000/gethistorydata',
method: "GET",
params: stock
}).then(function(result) {
alert("result.data"+result.data);
return result.data;
}).catch(function(fallback) {
alert("failed"+fallback + '!!');
});
}
}
});
In node js i have below :
app.get('/gethistorydata',function(req,res){
console.log("--------------->>>>>>");
console.log("stock name = "+req.params.data);
//res.cookie();
//res.sendFile("F:/customer/public/index.html");
});
req.params.data is undefined . whats wrong with syntax?

req.params refers to url path parameters. So you would have to add one to your route for it to be supported. For example a request to /gethistorydata/123 with this route defined(note the added /:id on the end):
app.get('/gethistorydata/:id, function(req, res) {
console.log('my id is ' + req.params.id');
});
would log "my id is 123".
I think you are looking for req.query. What does your stock object look like? If it looked like this {"price": 123} angular would modify the request to look like /gethistorydata?price=123 and you could change your code to this:
app.get('/gethistorydata, function(req, res) {
console.log('my stock price is ' + req.query.price');
});
which would log "my stock price is 123"
See the docs for more examples http://expressjs.com/en/api.html#req.query

Related

Request parameters showing as undefined

I'm trying to pass some URL params from a react component to a database query in a separate file. Here's a breakdown of what I'm trying to do:
TL;DR: the api request doesn't seem to have the category and city fields defined when I try to query the database.
1) Grab search params from a search form component
<Link to={"tours"+"/" + this.state.category + "/" + this.state.city} >
2) User clicks search, gets redirected to search results component. Once they are redirected, this function gets called. As I expect, the props are printing with the params from the search form.
componentDidMount: function() {
// console.log(this.props.route);
console.log(this.props.params.category);
console.log(this.props.params.city);
var category = this.props.params.category;
var city = this.props.params.city;
helpers.viewTours(
{
cat: category,
cit: city
}
).then(function(response){
var tours = response.data.length ? response.data[0].tour_title : 0;
console.log("RESPONSE " + response);
console.log("RESPONSE LENGTH " + response.data.length);
console.log("RESULTS ", tours);
//this.setState({trekList: response});
})
},
3) Using a wrapper function (helpers.viewTours) I want to pass those params from the search form into a database query
viewTours: function(searchParams){
console.log("search params " + searchParams);
return axios.get("/tours/search", searchParams);
},
4) This method gets called, but the params are undefined
router.get("/search", function(req, res){
var category = req.body.cat;
var city = req.body.cit;
console.log("tours cat " + category);
console.log("tours cit " + city);
Tour.find({}, function(error, doc) {
// Send any errors to the browser
if (error) {
res.send(error);
}
// Or send the doc to the browser
else {
res.send(doc);
//return doc;
}
});
});
Thanks,
According to axios documentation, axios.get(url, [config]) where config can be to send data with request, e.g. params field or data field. data field is not valid for GET request.
You can try the following to send params to backend.
viewTours: function(searchParams){
console.log("search params " + searchParams);
return axios.get("/tours/search", { params: searchParams });
},
and on server side, use req.params to fetch params from url.
router.get("/search", function(req, res){
var category = req.params.cat;
var city = req.params.city;
// rest of code
})

ExpressJS IP and AngularJS $http get

I'm trying to learn ExpressJS and I'm having trouble getting IP address from an Express route to display in the browser via Angular controller.
I'm using 2 Nodejs modules (request-ip and geoip2) to get the IP and then lookup geolocation data for that IP. Then trying to use Angular to display the geolocation data in the browser using an Angular $http get call.
My Express route for the IP:
// get IP address
router.get('/ip', function (req, res, next) {
console.log('requestIP is ' + ip);
// geolocation
geoip2.lookupSimple(ip, function(error, result) {
if (error) {
//return res.status(400).json({error: 'Something happened'});//default
return res.sendStatus(400).json({error: 'Something happened'});
}
else if (result) {
return res.send(result);
}
});
});
And my AngularJS controller code:
function MainController($http) {
var vm = this;
vm.message = 'Hello World';
vm.location = '';
vm.getLocation = function() {
$http({
method: 'GET',
url: 'localhost:8000/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
});
};
};
The Hello World message displays but not the location...? I can also go to localhost:8000/ip and see the JSON result. The result doesn't appear in Chrome's console either. The result is a json object like this:
{"country":"US","continent":"NA","postal":"98296","city":"Snohomish","location":{"accuracy_radius":20,"latitude":47.8519,"longitude":-122.0921,"metro_code":819,"time_zone":"America/Los_Angeles"},"subdivision":"WA"}
I'm not sure why the Hello Word displays and the location doesn't when it seems that I have everything configured correctly... so obviously I'm doing something wrong that I don't see...?
You have initialised 'vm.location' as a string when in fact it is a JSON object.
vm.location = {};
You need to adjust the url paramater in your request to:
url: '/ip'
As you are sending back JSON from Express.js, you should change your response line to:
return res.json(result);
Do you call vm.getLocation() somewhere in your code after this?
The data you need is under result.data from the response object.
Also in order to display the data in the html you have to specify which property to display from the vm.location object (vm.location.country, vm.location.city etc..).
From angular docs about $http:
The response object has these properties:
data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
Is this express js and angular hosted on the same port? If so please replace your
$http({
method: 'GET',
url: 'localhost:8000/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
});
with
$http({
method: 'GET',
url: '/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
});
It may be considered as CORS call and you have it probably disabled.
You can also specify second function to then (look code below) and see if error callback is called.
$http({
method: 'GET',
url: '/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
}, function (error) {
console.log(error);
});

Angular js how to pass data to delete service?

I am working in angular js on delete service api when passing data in service it is showing 400 bad request error.This is my js to call the service.
$scope.deleteUser = function(id){
var data = 'Id='+id;
DataService.deleteUser(data).then(function successCallback(response) {
console.log('deleted');
}, function errorCallback(response) {
console.log(response);
});
}
This is service js to delete users.
service.deleteUser = function(data){
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Auth-Token': 'mytoken'
}
};
return $http.delete(mainURL + '/users', data, config);
};
This is curl api request where i need to pass data:
curl -v -H "X-Auth-Token: mytoken" -X DELETE -F Id=665799088 http://<ipaddress>/users
The 2nd parameter to $http.delete is the config, so you need to pass the config object as the 2nd parameter and not data.
DELETE method type doesn't accept a Request body so you should not be passing the ID as data. Instead try this http://main_url/users?Id=id
So in your service use this
return $http.delete(mainURL + '/users?Id='+data, config);
Also check how you are passing the ID to your API. If you are passing ID as a query parameter then the above will work, but if you are passing it as a route parameter then the above URL won't work, but from your CURL expression I believe you are passing Id in the Query string and not as a route parameter.
According to documentation on $http service, delete method only accepts 2 parameters, url and config, meaning that your data is currently treated like config. You are most likely looking to pass some params options to your config object.
DataService.deleteUser(id).then(function successCallback(response) {
console.log('deleted');
}, function errorCallback(response) {
console.log(response);
});
And your service declaration should be more like.
service.deleteUser = function(id){
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Auth-Token': 'mytoken'
},
params : {
id : id
}
};
return $http.delete(mainURL + '/users', config);
};
Also keep in mind that a path looking like /users/id is more correct, if you are in charge of the API.

show current user information from node to angular

I want to show current user information from nodejs to angular(view).
The problem is that i don't know how to pass and how to get User Id in node and angular .
Code :
Node
router.get('/:id/api/data.json', function(req, res, next) {
console.log(req.params.id);
var userId = req.params.id;
User.findById({_id:userId}, function (err, doc) {
if (err) throw err
if (doc){
res.json({
doc: doc,
userID:req.params.id
});
}
});
});
Angular :
app.controller('profileCtrl', function($scope, $http) {
$http.get("don't know how to get id from node").then(function (response) {
console.log(response.data);
});
});
Your Node.js router is listening to the url /:id/api/data.json. The :id part of that means Node.js is expecting a paramater there, which will get picked up by req.params.id in your Node.js file.
This means that you actually have to be passing in an id value as a part of the url. So your url would look something like /userid12345/api/data.json.
In your Angular file, that's the url you're going to be making the get request to. Which means you need to know the user's ID in your Angular file so you can get that specific url, e.g.:
var userId = 'userid12345';
$http.get('/' + userId + '/api/data.json').then(function(response) {
console.log(response);
});
Once you pass userId in as a part of the url, then Node can grab it using req.params.id and you can make your db call.

PUT request not working in Node.js

I am trying to update an existing document in mongodb with node.js. But it does not seem to work. It do not even display the request call in the console. Please suggest what mistake I am doing or how I can I do the update operation in node.js with mongodb. Here is the code:
Node.js Code:
app.put('/addIssueId', function(req, res) {
console.log("Adding issue id")
console.log(req.body.issueKey)
impactMapFeature.update( {productName:req.params.productName, actor:req.body.actor, activity:req.body.activity,feature:req.body.feature},{issueKey:req.body.issueKey}, function ( err, data ) {
console.log("Updating" + data)
});
});
Angular Controller code:
var data = {
productName: $scope.productName,
actor: actor,
activity: impact,
feature : $('#feature').val(),
issueKey : data.key
};
$http.put('/addIssueId', data)
.success(function(data){
}).error(function(data){
console.log('Error in adding issueId' + data)
});
}
As chridam said, you are using req.params which is a route parameter. Either use the following route : /addIssueId/:productName or pass your variable with a query parameter : /addIssueId?productName=productName and {productName = req.query.productName, ... }, or pass your variable as you are doing it in the body (then you just need to change req.params.productName to req.body.productName

Resources