How to read request body dynamic attributes in express? - node.js

I am very new to express and have a small question. Actually I am a SAP developer, but learning express.
I have few form input text elements in JADE which are dynamically generated. The form elements which are generated dynamically are called optiondes1, optiondes2, optiondes3 and so on. Now, when I post the request, I can see in req.body all those input text values.
How to extract or read the dynamic text elements value from the request body (req.body). I am using body parser. Similarly, I also want to read the dynamic files elements named file1, file2, and so on from the req.files. Please advice.
for (var i = 0; i < numofoptions; i++){
var optcount = i + 1;
optdes = ('req.body.' + 'optiondes' + optcount);
// This prints req.body.optiondes1 as string, but I need the value of req.body.optiondes1
console.log(optdes);
optfile = 'file' + optcount;
origFileName = ('req.files.' + optfile + '.originalFilename');
console.log(origFileName);
};

Try:
optdes = req.body['optiondes' + optcount]
For more examples, search for things like: Converting string to variable name. (JavaScript)

Related

PugJS trying to use variable values on form attributes

I'm currently trying to make a quiz using PugJS. I'm trying to group the answers that are in the body when the form is posted.
Currently when I post the following form I get this data:
console.log(JSON.stringify(req.body));
returns the following: {"answer":["a","b","c","d","e","f"]}
All of the data is in the same "answer" object.
In my PugJS file I do the following:
block contents
form(action=url, method='POST')
each question in config
h1= question.question
.row.mb-3
- for (var x = 0; x < question.requiredAnswers; x++)
label.col-sm-2.col-form-label(for='answer') Antwoord #{x + 1}
.col-sm-10
input.form-control(type='text' name='answer' id='answer')
hr
button.btn.btn-primary(type='submit', value='Submit') Verzend de antwoorden
As you can see I keep using the same label(for='answer') and input(name='answer' id='answer')
I tried to use the variable x to change the objects to: label(for='answer #{x + 1}') and input(name='answer #{x + 1}' id='answer #{x + 1}')
The output I would like:
{"answer1":["a"], "answer2":["b","c"], "answer3":["d","e","f"]}
I also tried a escaping the variable using #{x + 1} but no luck!
The browser will submit form parameters only as simple key-value pairs. If there are multiple keys with the same name, they will be submitted as they are, repeatedly. I think it is the Express body-parser middleware that converts keys with the same names into an array.
In Express, req.body.someParameter is a string value if someParameter occurs only once in your form. It is an array of strings if that parameter is received more than once.
doctype html
html
body
//- Test data:
- const config = [ { requiredAnswers: 1}, { requiredAnswers: 2},{ requiredAnswers: 3}]
form(method="post")
each question,i in config
p Q#{i+1}
ul
- for (let x=0; x<question.requiredAnswers; x++)
label(for="Q"+i+"A"+x) Antwoord #{x+1}
input(name="answer"+(i+1) id="Q"+i+"A"+x)
br
input(type="submit")
The above labels when clicked will set focus to each respective input box correctly. When submitted with the same values you used, the browser sends the following in the request payload:
answer1=a&answer2=b&answer2=c&answer3=d&answer3=e&answer3=f
and req.body at the server is:
{"answer1":"a","answer2":["b","c"],"answer3":["d","e","f"]}

Find HTML Element value in Inline Code Connector Logic App

I am trying to get the value from an API multipart Response which contains json, xml and html. Plus HTML doesn't have any id and any class on its elements in that response. I want to get the complete table in an element and want to get the values from its tr. Please suggest me how can I do this in inline code in logic apps.
var response = workflowContext.trigger.outputs.body; // API Response
var multiBody = response.body.$multipart[4].body; // multipartBody
var table = multiBody. // How to get table section and get its tr values
return table;
I have already written the javascript code which I want to implement in inline code connector. My code is
var rows = document.getElementsByTagName('table')[4].rows;
var firstRow = rows[0]; // LTV/CLTV Row
var firstCell = firstRow.cells[1]; // LTV/CLTV Index
var firstText = firstCell.innerText;
var firstValue = firstText.substring(0, firstText.indexOf('/') - 1); // LTV
var secondValue = firstText.substring(firstText.indexOf('/') + 2, firstText.lastIndexOf('/') - 1); // CLTV
Please help me how can I do this.
Plus as it is mentioned in the documentation that we can write the javascript in inline code connector then why getElementById, getElementByTagname functions are not working here.
The Inline Code Actions runs NodeJS for JavaScript which doesn't really have a DOM Object to work with like a browser.
Instead, you will have to parse the DOM or just perform string searches to get what you need.
Parsing the DOM wouldn't be that simple of course and it would be best to use something like jsdom inside an Azure Function instead, if string/regex searches won't cut it for you.

Using composed xpath to locate an element and click on it

I am trying to retrieve a list of elements using XPATH and from this list I want to retrieve a child element based on classname and click it.
var rowList = XPATH1 + className;
var titleList = className + innerHTMLofChildElement;
for(var i = 0; i < titleList.length; i++) {
if(titleList[i][0] === title) {
browser.click(titleList[i][0]); //I don't know what to do inside the click function
}
}
I had a similar implementation perhaps to what you are trying to do, however my implementation is perhaps more complex due to using CSS selectors rather than XPath. I'm certain this is not optimized, and can most likely be improved upon.
This uses the methods elementIdText() and elementIdClick() from WebdriverIO to work with the "Text Values" of the Web JSON Elements and then click the intended Element after matching what you're looking for.
http://webdriver.io/api/protocol/elementIdText.html
http://webdriver.io/api/protocol/elementIdClick.html
Step 1 - Find all your potential elements you want to work with:
// Elements Query to return Elements matching Selector (titles) as JSON Web Elements.
// Also `browser.elements('<selector>')`
titles = browser.$$('<XPath or CSS selector>')
Step 2 - Cycle through the Elements stripping out the InnerHTML or Text Values and pushing it into a separate Array:
// Create an Array of Titles
var titlesTextArray = [];
titles.forEach(function(elem) {
// Push all found element's Text values (titles) to the titlesTextArray
titlesTextArray.push(browser.elementIdText(elem.value.ELEMENT))
})
Step 3 - Cycle through the Array of Title Texts Values to find what you're looking for. Use elementIdClick() function to click your desired value:
//Loop through the titleTexts array looking for matching text to the desired title.
for (var i = 0; i < titleTextsArray.length; i++) {
if (titleTextsArray[i].value === title) {
// Found a match - Click the corresponding element that
// it belongs to that was found above in the Titles
browser.elementIdClick(titles[i].value.ELEMENT)
}
}
I wrapped all of this into a function in which i provided the intended Text (in your case a particular title) I wanted to search for. Hope this helps!
I don't know node.js, but in Java you should achieve your goal by:
titleList[i].findElementBy(By.className("classToFind"))
assuming titleList[i] is an element on list you want to get child elements from

How do I search for a string and return the string's neighbor word from a text in google apps script?

I'm getting some spesific emails from gmail to a spreadsheet. But before I send them to spreadsheet. I want to get some spesific data from email plain text.
For example, there is a word "arrival" in the text and the date next to it. I want to get this date.
This is what I have so far:
function abepostalar() {
var threads = GmailApp.search('label:AOOA');
Logger.log(threads);
Logger.log(threads[0].getMessages());
Logger.log(threads[0].getMessages().length);
var messages;// = threads[0].getMessages();
var ContentEmail;// = messages[0].getBody();
for (var i = 0; i < threads.length; i++) {
messages = threads[i].getMessages()
ContentEmail = messages[0].getPlainBody();
// These are what I tried to find the word. not working.
//var bilgi = ContentEmail.findText("Uygar");
//var yazi = ContentEmail.asText().getText();
//Logger.log(bilgi);
//MesajlariDosyayaYaz(date); // a function to send date to the spreadsheet
}
}
I tried some other functions here and here couldn't nail it.
The value you get from messages[0].getPlainBody() is a string and it appears that you are trying document service methods which of course won't work. Try using javascript strings methods instead.

Extracting all text from a website to build a concordance

How can I grab all the text in a website, and I don't just mean ctrl+a/c. I'd like to be able to extract all the text from a website (and all the pages associated) and use it to build a concordance of words from that site. Any ideas?
I was intrigued by this so I've written the first part of a solution to this.
The code is written in PHP because of the convenient strip_tags function. It's also rough and procedural but I feel in demonstrates my ideas.
<?php
$url = "http://www.stackoverflow.com";
//To use this you'll need to get a key for the Readabilty Parser API http://readability.com/developers/api/parser
$token = "";
//I make a HTTP GET request to the readabilty API and then decode the returned JSON
$parserResponse = json_decode(file_get_contents("http://www.readability.com/api/content/v1/parser?url=$url&token=$token"));
//I'm only interested in the content string in the json object
$content = $parserResponse->content;
//I strip the HTML tags for the article content
$wordsOnPage = strip_tags($content);
$wordCounter = array();
$wordSplit = explode(" ", $wordsOnPage);
//I then loop through each word in the article keeping count of how many times I've seen the word
foreach($wordSplit as $word)
{
incrementWordCounter($word);
}
//Then I sort the array so the most frequent words are at the end
asort($wordCounter);
//And dump the array
var_dump($wordCounter);
function incrementWordCounter($word)
{
global $wordCounter;
if(isset($wordCounter[$word]))
{
$wordCounter[$word] = $wordCounter[$word] + 1;
}
else
{
$wordCounter[$word] = 1;
}
}
?>
I needed to do this to configure PHP for the SSL the readability API uses.
The next step in the solution would be too search for links in the page and call this recursively in an intelligent way to hance the associated pages requirement.
Also the code above just gives the raw data of a word-count you would want to process it some more to make it meaningful.

Resources