Request parameters showing as undefined - reactjs

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

Related

PUT Request with AngularJS and Express

When I'm performing a put request and console.log(response) of the request I only get a JSON Object like {"res":1} instead of getting the whole json object with its changes in order to update him in a database.
Controller :
$scope.doneEdit = function (components) {
console.log(components);
components.editing = false;
if (components.editing === false) {
$http.put('/propt/' + components._id).then(function (response) {
console.log(response.data);
});
}
}
Express
app.put('/propt/:id', function(req,res) {
console.log(req.body);
testDb.update({_id:req.params.id}, req.body, {}, function(err, numReplaced){
res.statusCode = 200;
res.send(req.body);
})
})
You should pass the data you want to send as a second parameter to put method:
$http.put('/propt/' + components._id, {someValue:components.someValue})
You can find the documentation here: https://docs.angularjs.org/api/ng/service/$http#put

unable to retrieve request param in node js

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

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 get URL parameter in Express?

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;

AngularJs - Send PUT request data as Form Data

I can't find a solution to send a PUT request data as Form Data in AngularJs.
Here's my code :
services.factory('appsInfoFactory', ['$http', function ($http) {
var apps = {};
var callPut = function (url, data, callback) {
var headers = {'Content-Type': 'application/x-www-form-urlencoded'},
User = 'aaaa',
Secret = 'dummysecret',
param = 'User=' + User + "&Secret=" + Secret;
$http.put(url + "?" + param, data, headers).success(callback);
};
apps.registerApp = function (appName, data, callback) {
callPut("/apps/" + appName, data, callback);
};
return apps;
}]);
$scope.addApps = function (Name, Repo, Root, Email, Internal, NonAtlantis) {
var User = 'aaaa',
Secret = 'dummysecret',
data = JSON.stringify({Name, Repo, Root, Email, Internal, NonAtlantis, User, Secret});
console.log(data);
appsInfoFactory.registerApp(name, data, function (val) {
console.log(val);
});
}
But it sends data as Request Payload and I want to send it as Form Data as per my backend code's requirement.
Thanks for any help.
Take a look at last line in the function callPut.
It should be like this :-
$http.put(url + "?" + param, data, {'headers': headers}).success(callback);
Last param to $http.PUT method is a config object in which it will be expecting a key as "headers" so try passing it as an object.
and I will suggest to make var config = {'headers':headers}
and then pass this config object to PUT.
$http.put(url + "?" + param, data, config).success(callback);

Resources