Parsing postdata value in nodejs - node.js

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

Related

How do you read/query the response body in API V2 of dialogflow-fulfillment?

In the v1, the request and response were specifically defined and read via -
console.log(request.body);
var input = request.body.queryResult;
In the v2, the request and response, both are wrapped inside the 'app'. My declarations of app are as below -
const {dialogflow} = require('actions-on-google');
const app = dialogflow({clientId: 'projectId'});
I have tried using the following but understood that it's not exactly the right way -
console.log(conv.request.body); //Getting undefined in console
//OR
console.log(app.request.body); //Getting undefined in console
var input = conv.request.body.queryResult;
Do I need to specifically mention request and response anywhere similar to the WebhookClient({request, response}) in V1?
Thanks in advance
After million trial and error, I finally found it and it's terribly simple
console.log(conv.body);
var input = conv.body.queryResult.queryText;
I know this seems to already be resolved. But I noticed that you did a console.log() on conv.body. Assuming this conv variable is the JSON response object you received from Dialogflow, I'd recommend doing console.log(JSON.stringify(conv)), which, not surprisingly prints the full JSON object to string in the console. This has saved me much time while trying to figure out the many JSON formats.

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.

Array as parameter in GET request in Postman

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("-");

How to get encoded data in node.js?

When I submit the html form getting post data in server side and when I console my data is displayed like hemant%40gmail.com this is my server side code:
if(req.url=="/user_login"){
var logindata='';
req.on('data',function(data){
logindata+=data;
});
req.on('end',function(){
console.log(logindata);
});
}
I don't know what u really want, but with JavaScript you can do:
logindata += decodeURI(data);
Hope u just need to decode your encoded string?!
// update
ok u have to use "decodeURIComponent(data)" to decode your string.
here is an example:
var test = '"user_email=hemant%40gmail.com&password=111'
var decode = decodeURIComponent(test).split("=")[1].split("&")[0]
console.log(decode);
note: this is an easy example, u have to parse to get your email out of the string (use regex).

NodeJS Express encodes the URL - how to decode

I'm using NodeJS with Express, and when I use foreign characters in the URL, they automatically get encoded.
How do I decode it back to the original string?
Before calling NodeJS, I escape characters.
So the string: אובמה
Becomes %u05D0%u05D5%u05D1%u05DE%u05D4
The entire URL now looks like: http://localhost:32323/?query=%u05D0%u05D5%u05D1%u05DE%u05D4
Now in my NodeJS, I get the escaped string %u05D0%u05D5%u05D1%u05DE%u05D4.
This is the relevant code:
var url_parts = url.parse(req.url, true);
var params = url_parts.query;
var query = params.query; // '%u05D0%u05D5%u05D1%u05DE%u05D4'
I've tried url and querystring libraries but nothing seems to fit my case.
querystring.unescape(query); // still '%u05D0%u05D5%u05D1%u05DE%u05D4'
Update 16/03/18
escape and unescape are deprecated.
Use:
encodeURIComponent('אובמה') // %D7%90%D7%95%D7%91%D7%9E%D7%94
decodeURIComponent('%D7%90%D7%95%D7%91%D7%9E%D7%94') // אובמה
Old answer
unescape('%u05D0%u05D5%u05D1%u05DE%u05D4') gives "אובמה"
Try:
var querystring = unescape(query);
You should use decodeURI() and encodeURI() to encode/decode a URL with foreign characters.
Usage:
var query = 'http://google.com';
query = encodeURI(query);
query = decodeURI(query); // http://google.com
Reference on MDN:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI
Decoding query parameters from a URL
decodeURIComponent cannot be used directly to parse query parameters from a URL. It needs a bit of preparation.
function decodeQueryParam(p) {
return decodeURIComponent(p.replace(/\+/g, ' '));
}
console.log(decodeQueryParam('search+query%20%28correct%29'));
// 'search query (correct)'
SOURCE: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent#decoding_query_parameters_from_a_url
#**update may-2020**
# how to use an encoder/decoder on node js
### I am writing my answer due to I have noisy data I spend 4 hour to fixed
data email input = myemail#gmail.com
data URL input = /us/home
```
decodeURI function that only decodes a URL special character
email output =>myemail%40gmail.com
url output => %2Fus%2F
using decodeURIComponent
email output = > myemail#gmail.com
url output => /us/
```
here some clarification where you can use decodeURI and decodeURIComponent a fucntion

Resources