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

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)

Related

Can't parse JSON from POST request using express in react

I'm having a problem parsing my JSON request using express, and after many hours of trying to research it, I can't figure out what the problem is.
Here is my code snippet
app.post('/Information', (req, res)=> {
console.log(req.body); // this prints out the exact POST request from Postman
const info = JSON.parse(req.body); // this returns SyntaxError: Unexpected token o in JSON at position 1
let insertQuery = `insert into Information(id, name, number, message)
values(${info.id}, '${info.name}', '${info.number}', '${info.message}')`
client.query(insertQuery, (err, result)=>{
if(!err){
res.send('Insertion was successful')
}
else{ console.log(err.message) }
})
client.end;
})
I know the reason behind the parsing error, trying to parse an 'o', because req.body is an object, but I tried the three methods of accessing properties of an object, and I get 'undefined'. I don't know if this will help, but if I send this POST request { "id":"3", "name":"Mark Zuckerberg", "number":"1112223333", "message":"Welcome to Facebook!" } from Postman, then this is what console.log(req.body) will print out {'{\r\n "id":"3",\r\n "name":"Mark Zuckerberg",\r\n "number":"1112223333",\r\n "message":"Welcome to Facebook!"\r\n}\r\n': ''}. This output looks odd to me because of the (: '') at the end, as it makes it look like there are only 2 properties for some reason and I don't understand why that's happening. I would be glad to try out any ideas you guys have, because I'm really lost right now. Thank you in advance.

Send body JSON with Postman in a POST method to execute procedure in ms sql server

I want to send a JSON (body) on Postman with POST method and receive a result.
Im a trainee and my boss asked me this. I've been looking in web for a week and didn't find. I said to him that method to receive a data is GET, but he said that GET has a limit on URL. If the stored procedure have a lot of parameters we will not receive the expected result, so a I have to use Post method.
This is my code to connect to ms sql server:
var express = require('express');
var app = express();
var sql = require('mssql');
var config = {
user: 'MY_USER',
password: 'MY_PASS',
server: 'MY_SERVER',
database: 'MY_DB'
};
Searching in google I found a way to execute a procedure with GET method. In the browser I put the value I want and I receive the result, but is not still what he wants. The code is:
app.get('/get/:pNU_EST001', function (req, res) {
//conexão com o DB
sql.connect(config, function(){
var request = new sql.Request();
request.input('pNU_EST001', req.params.pNU_EST001);
request.execute('dbo.ESTSP004_ConsultaLivrosEmprestadosAluno_XX', function(err, recordsets, returnValue, affected) {
if(err) console.log(err);
res.send(recordsets);
//res.end(JSON.stringify(recordsets)); /*--- result in JSON format ---*/
});
});
});
On Postman he showed me a example with DB2, but I couldn't see the code. On Post Method, on HEADERS it has two key:
KEY => Content-Type (value: application/json) // KEY => Accept (value: application/json)
And in his example, on BODY, he wrote a JSON like: { "pNU_EST001" : "3"} and received the related result below. That's what I need.
Express has a few other verbs to use you are using
app.get but there is also app.post if you change your code to use the latter instead it will handle a post request
app.post('/path', function (req, res) {
Then in express to get values from the POST body you get that from
req.body property
So in your case you would want to use req.body.pNU_EST001 instead of req.params.pNU_EST001

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

Function is getting undefined parameter Node.js

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.

Using the PUT method with Express.js

I'm trying to implement update functionality to an Express.js app, and I'd like to use a PUT request to send the new data, but I keep getting errors using PUT. From everything I've read, it's just a matter of using app.put, but that isn't working. I've got the following in my routes file:
send = function(req, res) {
req.send(res.locals.content);
};
app.put('/api/:company', function(res,req) {
res.send('this is an update');
}, send);
When I use postman to make a PUT request, I get a "cannot PUT /api/petshop" as an error. I don't understand why I can't PUT, or what's going wrong.
You may be lacking the actual update function. You have the put path returning the result back to the client but missing the part when you tell the database to update the data.
If you're using MongoDB and ExpressJS, you could write something like this :
app.put('/api/:company', function (req, res) {
var company = req.company;
company = _.extend(company, req.body);
company.save(function(err) {
if (err) {
return res.send('/company', {
errors: err.errors,
company: company
});
} else {
res.jsonp(company);
}
})
});
This mean stack project may help you as it covers this CRUD functionality which I just used here swapping their articles for your companies. same same.
Your callback function has the arguments in the wrong order.
Change the order of callback to function(req, res).
Don't use function(res, req).
Also if you want to redirect in put or delete (to get adress), you can't use normal res.redirect('/path'), you should use res.redirect(303, '/path') instead. (source)
If not, you'll get Cannot PUT error.
Have you been checking out your headers information?
Because header should be header['content-type'] = 'application/json'; then only you will get the update object in server side (node-express), otherwise if you have content type plain 'text/htm' like that you will get empty req.body in your node app.

Categories

Resources