How to get URL parameter in Express? - angularjs

I have a problem with getting URL parameter in Express.
On the client (Angular) I define state (ui.router) and send URL (id) with new state:
.state('home.detail', {
url: '/:id',
templateUrl: 'views/detail.html',
controller: 'DetailController'
});
On the backend, I'm trying to get this URL(id)
app.get('/api/:id', function(req,res){
var id = req.query.id;
console.log(id);
var queryString = "SELECT * FROM `table` WHERE table.ID=id";
//add to a callback
connection.query(queryString, function (error, results) {
if(error) {
throw error;
}
else {
// send JSON object to the client
res.end(JSON.stringify(results));
//console.log(res);
}
});
});
but I got undefinedvalue of id (console.log(id)).
What I'm doing wrong?

You should use this instead :
var id = req.params.id;
req.params contains route parameters (in the path portion of the
URL)
req.query contains the URL query parameters (after the ? in
the URL).

The :id gets put in the params object in the request. So, all you have to do to get it is do:
var id = req.params.id;
Also, when you build your queryString you need to pass it the value of id instead of a string called "id". You would have to do something like this:
var queryString = "SELECT * FROM `table` WHERE table.ID=" + id;

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
})

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.

How to post or get into MVC controller?

I have a problem. I have this dropdown list :
#Html.DropDownListFor(m => m.SelectCountryId, Model.Countries, #Translator.Translate("PLEASE_SELECT"), new { id = "CountryID", #class = "form-control",ng_model="countryId", ng_change = "LoadRegions(countryId);", #required = "required" })
And i need on ng_change to get into MVC controller that looks like this:
[AllowAnonymous]
public JsonResult GetRegions(int countryId) // return a JsonResult
{
IUserManager manager = UserFactory.GetUserManager(WebConfiguration.DefaultTerminalId);
var model = manager.GetRegions(countryId);
return Json(model, JsonRequestBehavior.AllowGet);
}
This is script in angular:
$scope.LoadRegions = function (countryId)
{
console.log("COUNTRY ID: ", countryId);
$http.post('/app/Account/GetRegions/'+ countryId).then(function (response)
{
alert(response);
});
}
I get country ID but in console i get this error:
POST http://localhost:60789/app/Account/GetRegions/4 500 (Internal Server Error)
The default routing in MVC allows for {controller}/{action}/{id} but your controller is expecting {controller}/{action}/{countryId}.
You can change your call to look like:
GetRegions?countryId=XXX
Or change your method signature to look like:
public JsonResult GetRegions(int id)
Or, if you really want to, you can accommodate this route in your RouteConfig.cs
Edit: I just realized you're calling this with $http.post but everything in your code suggests you want this to be a GET, so I'd change your angular code to $http.get()
From the looks of it there are a few problems in your javascript.
Try the following.
$scope.LoadRegions = function (countryId)
{
var params = {};
params.countryId = countryId;
console.log("COUNTRY ID: ", countryId);
$http.post('/Account/GetRegions/', params).then(function (response)
{
alert(response);
});
}
As you can see you're passing in the params object with the country ID, you are making a call to the POST on the server side also -> Seperate to the angular app folder.

GET Request Without Key in URL - Angular JS

I have a GET endpoint like the following:
http://test.com/api/test/1234
where 1234 is the value of the key. The URL only looks for the value of the key and not the key name itself.
I tried using:
var params = {'': vehicleId};
to set the parameter, but the resulting URL looks like:
http://test.com/api/test?=237819
How do I hit my API in the above format using Angular's $Resource .get() method?
The resource has to be defined as:
var Vehicle = $resource('/api/test/:vehicleId', { vehicleId: '#id' });
and then the resource can be used as:
Vehicle.get({vehicleId: 1234}, function(data) {
console.log("data", data);
});

Post Using Resource Causes Parameters to be Appended to URL - Angular JS

I have the following service in my Angular App:
myAngularApp.factory('myFactory', function($resource, HOST){
return{
getThings: function(userId, userToken){
var connection = $resource(HOST + '/user/mypost/', {'Userid': userId, 'UserToken': userToken, 'Type': 'Read'}, {
save: {
method: 'POST'
}
});
var results = connection.save();
results.$promise.then(function(data){
results = data;
});
return results;
}
}
});
In one of my controllers, I call the above factory and its function using
myFactory.getThings($scope.someId, $scope.someToken);
When I look at the Network pane in developer tools, the POST request is sent with the correct query string parameters, but the URL is appended with the same parameters (a la GET request). How do I stop the parameters from being appended to my URL?
Try passing your parameters directly to your save() function and remove them from the URL parameters argument in your $resource constructor:
var connection = $resource(HOST + '/user/mypost/', {}, {save: {method: 'POST'}});
var params = {'Userid': userId, 'UserToken': userToken, 'Type': 'Read'};
var results = connection.save(params);

Resources