Array as parameter in GET request in Postman - node.js

I have to send array of ids in GET request as paramenter.How can I test it in Postman(google chrome extension for API testing)?
The scenario is I have url, www.something.com/activity/poi_ids
poi_ids should conatain arrays of ids like [316,318]
At api side using express,
app.get('/activity/:poi_ids',function(req,res){
var poi_ids = req.params.poi_ids;
.......
.......
});
I have looked into it but it is only for post request

you can send them via query params ..
in your http query params assign all values to same variables like
GET activity?pid=12&pid=23&pid=34
and then inside your express get it like
var ids=req.query.pid; //[12,23,34]

It is unstructured text. If you want to "send an array" then you'll need to design some way to encode it and then write JavaScript to decode it.
For example:
GET /activity/316-318
and
var poi_ids = req.params.poi_ids.split("-");

Related

how to get records from mongodb through node js

Here In my mongo collection I have few records. I am writing an API in node js where I pass the ID in request body. My API have to take ID from request body and need to fetch it's whole records in response. but I am getting empty array.
My mongo collection record:
[{ accountId:"a1",name:"test"}]
My Node js code approach:
exports.getById = async (req) =>{
let id = `"` + req.body.accountId +`"`;
let accountId = await db.collection('account-details').find({id}).toArray();
return accountId
}
In request body, I am passing accountId as :
{
"accountId":"a1"
}
The ID is in the form of string. When I am trying to fetch whole records with the provided ID through my API, I am getting response as []. Can anyone please help me on this
You cannot send a body with an HTTP GET, therefore it will not be available in the req object, so req.body.accountId will be undefined and id will be an empty string.
You need to use POST (or PUT) to send body data.
But the more usual solution in your situation is to use GET with dynamic routing, where you add the id to the route e.g.: http://example.com/api/accounts/1234
If you use Express, in your router you need to add the route api/accounts/:id to your router. The id will be available in your code as req.params.id.
See Express docs. For other frameworks this will be something alike.
Hope this helps.

Unable to validate Twilio request in Google cloud function

I have a Google cloud function to which Twilio sends POST requests with SMS statuses but I am unable to verify that the requests are coming from Twilio using any of the methods outlined in https://www.twilio.com/docs/usage/security
My first attempt consisted of using the validateRequest function, as shown in the code below
const twilio = require('twilio');
let url = 'https://....cloudfunctions.net/...'
let token = 'XXXX';
let header = request.headers['x-twilio-signature'];
let sortedKeys = Object.keys(request.body).sort();
let sortedParams = {};
sortedKeys.forEach(key => {
sortedParams[key] = request.body[key];
});
let validated = twilio.validateRequest(token, header, url, sortedParams);
I confirmed that the value of token matched the auth token from the Twilio account settings, sortedParams contained alphabetically sorted camel-cased Twilio request params and the url matched that which was passed to the Twilio client when creating the SMS. However, validateRequest would always return false.
My next attempt involved hashing the combination of the url and request params by copying the code from https://www.twilio.com/docs/libraries/reference/twilio-node/3.18.0/webhooks_webhooks.js.html
const crypto = require('crypto')
sortedKeys.forEach(key => {
url = `${url}${key}${request.body[key]}`;
});
let signature = crypto
.createHmac('sha1', token)
.update(Buffer.from(url, 'utf-8'))
.digest('base64');
Upon comparing the value of signature to that of the header, the two never matched.
Twilio developer evangelist here.
I recommend using the validateRequest method as that does most of the work for you.
You don't need to perform the parameter sorting that you've attempted, JavaScript objects are unordered and the library sorts and appends the parameters to the URL string already.
Things you need to check are that the URL is the exact webhook URL you set in your Twilio console, including the entire path and any query parameters that are included.
Also, have you ensured that request.body is populated and that your express app is using body-parser to parse the incoming request as url encoded form parameters?
app.use(bodyParser.urlencoded({ extended: false }));
If you are trying to validate the request as middleware, make sure that the request validation is done after body parsing.
Does any of that help at all?
It turns out that the there was nothing wrong with the validateRequest but rather the way I was declaring the token. Instead of hard-coding it in the function's code, it was being retrieved from a Google storage bucket as a buffer and then converted to a string. For unknown reasons, even though visually, the retrieved value matched the original token, a === comparison returned false. Once I hard-coded the token, everything worked.

node.js request post retrieve last id from db.json

After posting in db.json a new record (transaction with several data), I would like to get the id of the new record before going on. How-to do it ? I am stuck
I have in my db.json a "table" positions with an id automatically generated
my request is
request({
url: url + '/api/positions,
method: 'POST',
form: transaction
}, ????);
I want in my callback retrieve position.id (as I have to use it in another part of code).
Thanks a lot
Olivier
Make sure your API is giving back the position id, Im assuming you're using express, so in /api/positions have the response be res.send({position...});
EDIT, So you're asking about routing? Here is an awesome guide: https://expressjs.com/en/guide/routing.html but Ill give you an example of what I mean.
app.post('/api/positions', function(req, res) {
//your logic goes here, so you are sending a 'transaction' object
// npm install and use body parser so you can retrieve attributes
// from the body of the post
res.send({position: x})
})
Maybe some thing like that.
...
var router = jsonServer.router('db.json');
...
// 'router.db.get' will fetch any first level attribute from your db.json
var positions = router.db.get('positions').value();
var lastPosition = positions[positions.length-1];

Error while getting parameters from request object containing `&` character

I'm trying to get param from request object using following code.
module.exports = function (req, res) {
var query = req.query;
var data = JSON.parse(query.param1);
}
This is working fine for most of the cases.
If param1 contains & character then query.param1 get values before & and next values are considered as new param.
eg
localhost/?param1={"url":"http://s.test.com/x?format=jsonp&id=a&callback=b"}
Edit original url is already encoded
localhost/?param1=%7B%22url%22%3A%22http%3A%2F%2Fs.test.com%2Fx%3Fformat%3Djsonp%26id%3Da%26callback%3Db%22%7D
in this case I'm getting param1 = {"url":"http://s.test.com/x?format=jsonp
which is not valid json, so I'm getting error, currently we've solved it using regex (removing localhost/?param1= part of url).
What's best way to handle this use case?
Edit : server environment
centos 6.5 server
node v0.12.7
express#4.13.3
req.query is already an object with express :
An object containing a property for each query string parameter in the route. If there is no query string, it is the empty object, {}.
req.query documentation
You have to encode your URL before calling nodejs API. And on the nodejs side, you have to decode the URL to get correct parameteres.

Parsing postdata value in nodejs

I have a post data in the format below
authInfo={"user":"1","password":"a"}
How do I get the key ie authInfo. I am stuck here! req.query did not work out. Any help will be much appreciated.
Data transmitted via POST could be found in req.body.
For your example:
req.body.authInfo
Also: You need a data parser enabled, otherwise the Post data will not be decoded. I assume you use express, so you would need app.use(express.bodyParser()).
var authInfo = {"user":"1","password":"a"}
var user = authInfo.user
var pass = authInfo.password
// user = 1 , pass = a

Resources