Function is getting undefined parameter Node.js - javascript

I'm working with an application that uses Mongo as DB and node.js. I created a function which is meant to recieve a parameter named orderedBy but my console.log, prints an undefined parameter. Why is this happening? Here's the code.
exports.showAll = function(orderedBy, callback){
var query = {orderedBy: orderedBy}
console.log("Orderer by ===== "+ orderedBy);
var array = models.Orden.find(query).lean().exec(function(err, orders) {
if( orders.length > 0) {
callback({'array' : orders});
//callback({'array' : JSON.stringify(orders)});
}
else {
callback({'error' : "You don't have any orders"});
}
});}
And here i call showAll
app.post('/api/showAll', function(req, res) {
var orderedBy = req.body.orderedBy;
ordenes.showAll(orderedBy, function(found){
console.log(found);
res.json(found);
});
});
Basically, what I want is get an ID and show how many orders that person has. But my response is always "You don't have any orders" mainly because me console log, shows that orderedBy is undefined.
And yes i'm making sure i'm sending the correct ID, simulating it with Postman

your req request object have two properties called
body: when you send a POST/PUT request will be populate by the body of the request
query: when you send a request, (no matters the method) will be populate by the queryString. example http://localhost:3000?orderBy=AAAA
on your server side you can can req.orderBy === 'AAAA'

Thought it was my function being wrong, but it was my parameters. I was stupidly sending form-data, instead of x-www-form-urlencoded in postman. It was never broken, thanks.

Related

Sending an object, in a get request, in params, in postman

I'm new here on the site, I opened this user a few days ago.
I want to send in a get object request, I do it through the postman.
I'm trying to do it, but it's not working for me, I probably have a little problem somewhere.
This is what I'm trying to do.
In postman:
Axios get request:
app.get('/realtimeConversations', FBAuth, getRealtime);
The function I run on the server side.
exports.getRealtime= (req, res) => {
console.log(JSON.stringify("testing"));
console.log(JSON.stringify(req.query));
console.log(req.query.user);
console.log(req.query.user.uid_1);
console.log(req.query.user.uid_2);
return res.json([]);
}
i try to use JSON.parse instead but this is not working for me:\
exports.getRealtime= (req, res) => {
console.log(JSON.stringify("testing"));
console.log(JSON.stringify(req.query));
console.log(JSON.parse(req.query.user));
console.log(JSON.parse(req.query.user).uid_1);
console.log(JSON.parse(req.query.user).uid_2);
return res.json([]);
}
I can get the object, but I can't access the values inside it
These are the prints I get on firebase:
what you are using currently is :
{ uid_1: "user.handle", uid_2: "userUid" }
here the key name which is a string is not enclosed with doublie quotes so its not a valid json and hence JSON.parse will fail.
use query parameter as :
{ "uid_1": "user.handle", "uid_2": "userUid" }
you can check this is in postman side itself .
Try the below code in postman pre-request or test scrit
console.log(JSON.parse(pm.request.url.query.get("user")).uid_2)

Changing req object within api server?

I recently picked up a client who has a dev team. I am working on a website that has already been developed and am running into some things that are slightly strange to me.
I've always though it was essentially bad to mess with the request object within route handling (I could be completely wrong here).
The following code reaaaaally confuses me as I am not sure why they are assigning the req.query.msg to something instead of just creating a variable and passing it through on the ejs page render.
/********************************************************
* *
* CHANGE PASSWORD ROUTE THAT POSTS THE NEW PASSWORD TO *
* DATABASE. *
* *
********************************************************/
app.post('/client/password', function (req, res) {
var url = URLS.ClientChangePW;
if(req.session.securityquestions[0].SSN !== "null" || req.session.securityquestions[0].SSN !== "undefined"){
if(req.body.pwd !== req.body.pwdconf){
res.redirect('/client/changePassword' + config.PWD_MISMATCH);
} else {
var ssn = req.session.securityquestions[0].SSN;
while(ssn.length < 9){
ssn = "0" + ssn;
}
url = url.replace("#ssn", ssn);
url = url.replace("#newpw", req.body.pwd);
}
request.put(url, function (err, xres, body) {
var data = JSON.parse(body);
if(data.status === 200){
email(req.session.securityquestions[0].EMAIL, "none", "forgotpw", function(result){
if(result){
req.query.msg = "Your password has been reset.";
} else {
req.query.msg = "Request unsuccessful. Please call number here for assistance.";
}
res.render('pages/login', {
session: req.session,
msg: req.query.msg
});
});
} else {
req.query.msg = "Request unsuccessful. Please call number here for assistance.";
res.render('pages/login', {
session: req.session,
msg: req.query.msg
});
}
});
}
});
Again, I have never really messed with the req object so I could be wrong. I always thought the client sets up the request and we use that to send a response.
I am not sure why they are assigning the req.query.msg to something instead of just creating a variable and passing it through on the ejs page render.
There does not appear to be any reason to be assigning to the req.query.msg property here. If this were my code, I'd be using a separate local variable for it.
Again, I have never really messed with the req object so I could be wrong. I always thought the client sets up the request and we use that to send a response.
Though this is not what is happening here, it is common in Express development to use middleware that sets state on the req object for request handlers further down the routing stack to use. The req object is the canonical object where you keep request-specific state while processing the request. If you only have one request handler function working on the request, then there's no reason to put state on the req object as you can just use local variables in that one request handler function. But, if you're using middleware whose job it is to set things up before ultimately getting to a request handler, then the req object is where that setup state is usually put. You'll notice that req.session is also used in this code. That .session property was put there by some middleware upstream in the request processing.
So, it IS common to add state to the req object when using middleware. But, in the .msg property example in the code you show, there is no particular reason to put that on the req object as its value is only needed in the local function so it can just as easily (and I would argue more clearly) be in a local variable.

How to run one request from another using Pre-request Script in Postman

I'm trying to send an authenticated request with one click in postman.
So, I have request named "Oauth" and I'm using Tests to store the token in a local variable.
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", jsonData.access_token);
What I'm trying to do now is that run the Oauth request automatically (from a pre-request script) for any other requests which needs a bearer token.
Is there a way to get an access token and send an authenticated request with one postman button click?
As mentioned by KBusc and inspired from those examples you can achieve your goal by setting a pre-request script like the following:
pm.sendRequest({
url: pm.environment.get("token_url"),
method: 'GET',
header: {
'Authorization': 'Basic xxxxxxxxxx==',
}
}, function (err, res) {
pm.environment.set("access_token", res.json().token);
});
Then you just reference {{access_token}} as any other environment variable.
NOTE: There now is a way to do this in a pre-request script, see the other answers. I'll keep this answer for posterity but just so everyone knows :)
I don't think there's a way to do this in the pre-request script just yet, but you can get it down to just a few clicks if you use a variable and the Tests tab. There are fuller instructions on the Postman blog, but the gist of it is:
Set up your authentication request like normal.
In the Tests section of that request, store the result of that request in a variable, possibly something like the following:
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", data.token);
Run the authentication request -- you should now see that token is set for that environment (click on the eye-shaped icon in the top right).
Set up your data request to use {{token}} wherever you had previously been pasting in the bearer token.
Run your data request -- it should now be properly authenticated.
To refresh the token, all you should need to do is re-run the authentication request.
You can't send another request from Pre-request Script section, but in fact, it's possible to chain request and run one after another.
You collect your request into collection and run it with Collection Runner.
To view request results you can follow other answer.
The same question was on my mind, which is basically "how can I run another request that already exists from another request's test or pre-request script tabs without building that request with pm.sendRequest(reqConfObj)?", then I found the postman.setNextRequest('requestName') method from this Postman discussion which is gonna lead you to this postman documentation page about building request workflows.
But the thing is, postman.setNextRequest() method will not run if you are not running a folder or a collection, so simply hitting the 'Send' button of the request that has your script won't work.
I also would like to draw your attention towards some things:
The prepended word, it's 'postman' instead of 'pm'.
postman.setNextRequest() will always run last, even though you have written it to the top of your script. Your other code in the script will be ran and then postman.setNextRequest will initialize.
If you would like to stop the request flow, you could simply postman.setNextRequest(null).
I would encourage everyone that uses Postman to check out the links that was mentioned, I believe it's a great feature that everybody should give it a try! :)
All these workarounds with recreating requests. Postman does not support what you want to do. In order to get what you want, you have to use Insomnia, it allows you to map body values from other request responses and if those responses are not executed ever it automatically runs them or behaves based on chosen policy.
But if you want to stick with Postman, then you'll have to save full previous request params to global variables, then retrieve all configuration of previous requests from that variable as a JSON string, parse that JSON into an object and assign it to pm.sendRequest as the first argument.
You can add a pre-request script to the collection which will execute prior to each Postman request. For example, I use the following to return an access token from Apigee
const echoPostRequest = {
url: client_credentials_url,
method: 'POST',
header: 'Authorization: Basic *Basic Authentication string*'
};
var getToken = true;
if (!pm.environment.get('token')) {
console.log('Token missing')
} else {
console.log('Token all good');
}
if (getToken === true) {
pm.sendRequest(echoPostRequest, function(err, res) {
console.log(err ? err : res.json());
if (err === null) {
console.log('Saving the token');
console.log(res);
var responseJson = res.json();
console.log(responseJson.access_token);
pm.environment.set('token', responseJson.access_token)
}
});
}
First, add pre-request script:
pm.sendRequest({
url: 'http://YOUR_SITE',
method: 'POST',
body: {
mode: 'urlencoded',
urlencoded: [
{ key: "login", value: "YOUR_LOGIN" },
{ key: "password", value: "YOUR_PASSWORD" }
]
}
}, function (err, res) {
if (err === null) {
pm.globals.set("token", res.json()["access_token"]);
}
});
Second, set custom variable(after you can use it value):
Third, you can use variable by {{VARIABLENAME}}, for example:
If you are setting token in your auth token you can copy its request configuration to env once (in test script section) and automatically call it from other request and use token from env.
It originally mentuioned here: https://community.postman.com/t/use-existing-postman-request-in-pre-post-script/23477/5
Copy current request config to env in auth test script:
let r=pm.response.json();
pm.environment.set("access_token", r.access_token);
pm.environment.set("refresh_token", r.refresh_token);
pm.environment.set("auth_req", pm.request);
And then call it on other endpoints:
pm.sendRequest(pm.environment.get("auth_req"))
I have tried multiple solutions, the below solution is related to when you are parsing the response for request 1 and passing any variable into the second request parameter. ( In this Example variable is Lastname. )
Note:- data and user are JSON objects.``
postman.clearGlobalVariable("variable_key");
postman.clearEnvironmentVariable("variable_key");
tests["Body matches string"] = responseBody.has("enter the match string ");
var jsonData = JSON.parse(responseBody);
var result = jsonData.data;
var lastName = result.user.lastName;
tests["Body matches lastName "] = responseBody.has(lastName);
tests["print matches lastName " + lastName ] = lastName;
You can use a function sendRequest of postman.
Some examples here.
https://gist.github.com/sid405/b57985b0649d3407a7aa9de1bd327990

request.body.email is undefined node js server side using http.get

I have a problem where request.body.email returns me undefined.
I wrote this code on my controller on my client side:
wish.controller('wishCtrl',['$scope','$http','$cookies',function($scope,$http,$cookies) {
var user={};
user.email = $cookies.get('cookieEmail');
console.log(user.email);
$http.get("http://localhost:3000/wishlist",user).success(function(data){
$scope.wishController = data;
console.log(data);
});
}]);
here I see - user.email ok so there is no problem here.
on my controller on my server side I wrote:
exports.getData = function(request, response) {
userEmail = request.body.email;
console.log(userEmail);
}
which writes me back undefined.
to call this function I have on my server.js (on the server side)
app.get('/wishlist',wish.getData);
any idea how to fix it?
You are making a GET request. There is no request body in a GET request.
If you want to read query string data then parse request.url.
The Angular documentation for get says that the last argument must be a configuration object. So it looks like you aren't even managing to put your data in the URL either. Pass a configuration too.
$http.get("http://localhost:3000/wishlist",user, {})
because i't get function have to pass the email on the client side this way:
$http.get("http://localhost:3000/wishlist/"+user.email)
and the path of the sever should recognize it that way:
app.get('/wishlist/:email',wish.getData);
and int the controller that way:
userEmail = request.params.email;
console.log(userEmail);

Json returns undefined in nodeJs and AngularJs

I've got an app which makes calls to an api and shows data about that info: first, it takes a username from an input in the client and posts it to the server. In this step if I check if the data has been sent alright to the server everything seems fine.
AngularJs part:
var app=angular.module("app",[])
app.controller("InfoController",['$scope','$log','$http','$filter',function($scope,$log,$http,$filter){
$scope.info = {
summonerName: '',
};
$scope.info.onClick = function(){
$scope.info.summonerName = $scope.info.summonerNameBox;
$http.post('/api/getSummonerName', $scope.info);
$http.get('/api/summonerData')
.success(function(data, status){
$scope.info.display = data;
}).error(function(data,status){
alert("Error: " + status);
});
};
}])
Nodejs:
var summonerName;
var summonerId = '';
app.post('/api/getSummonerName', function (req, res){
summonerName = req.body.summonerName;
console.log("Post getSummonerName " + summonerName);
});
app.get('/api/summonerData', function(req,res){
LolApi.Summoner.getByName(summonerName, function(err, summoner) {
if(!err) {
res.json(summoner);
summonerId = req.body.summoner;
console.log(summonerId);
if(err)
res.send(err)
}
})
});
When I have this data in the server, I make a call to an api for getting this user's info, and everything goes fine as well.
The problem comes when I want to store an specific field from this json. When I want to store it in a variable, everything I get is "undefined" :/ (Once I achieved getting "[Object object]", but can't get it anymore...)
Any idea?
Thank you all.
In my opinion, this isn't the way you should do it.
If you want to do a get on a summoner, you need to just use the get method.
Especially if you're dealing with multiple users.
You might want to pass data in the get request like specified in this answer and ditch the post request:
AngularJS passing data to $http.get request
That way, you're not dependent on the memory and you're able to modularize it :)

Categories

Resources