How I can fetch textarea data to node js - javascript

I cannot send data of <textarea> to node js, Node js don't see the my sent data.
For Fetch data to Node Js
continueBtn.addEventListener("click", async () => {
console.log(myMsg.value)
console.log(typeof(myMsg.value))
const req = await fetch("/sendmsg", {method: "POST",body: myMsg.value}) ;
console.log("Fetched")
})
For get data in Node js
const {userMessage} = Object.keys(req.body)

You are passing a string to body. Since you aren't overriding it, it will be given a text/plain content-type.
On the server you expect req.body to contain an object.
You haven't shown us what, if any, body parsing middlewares you have configured in your server side code, but none of the common ones will convert something that is text/plain into an object.
You should:
Make sure that you have a body parsing middleware configured
Encode the data you are passing to body (e.g. with URLSearchParams) so it has name=value pairs instead of being a plain string.
If you end up passing a string (e.g. if you pass a string of JSON instead of a URLSearchParams object) then you'll also need to set a Content-Type request header that matches your data format.

"const {userMessage} = Object.keys(req.body)"
I don't see why you'd be expecting to have a userMessage key in your body object with the code you pasted. It's possible the data is being passed properly, but you are trying to access the wrong key. I would try logging in your server code to debug the response format as a first step:
console.log(JSON.stringify(req.body))
Let me know if that gets you enough help to move forward, and I can circle back here if not.

Related

REST API: How to compress JSON for POST method

I am calling a REST API in my project for creating some records.
Everything is working fine but I got a challenge, the JSON request body is too big (having thousands of keys and values).
Now I want to compress the request body. I tried it using JavaScript
var reqJSON = { ... } // too big JSON object
var compressedJSON = JSON.stringify(reqJSON, null, 0); // converting JSON to String (compression)
Now I am sending the string in the request body and converting this string into JSON at the server-side.
I am curious, is it the correct way of JSON compression? If yes how can I check the difference in the request body size?
Thanks for your time.
That isn't compression at all.
var reqJSON = { ... } // too big JSON object
That will give you a JavaScript object, not JSON. Possibly your Ajax library will convert it to JSON if you pass it. There's no way for us to know. If the data is to get to the server then it will need serializing to some format that can be sent over the wire so something must be converting it before the HTTP request is made.
var compressedJSON = JSON.stringify(reqJSON, null, 0); // converting JSON to String (compression)
That will give you JSON. There's no compression involved though.
If you want to compress it then you'd need to look for a library that can do actual compression.
You can use gzip for compress json its working fine

How can I make HTML fill itself with the content from the JSON file using handlebars?

I need to make HTML fill itself with content from JSON file using Mustache or Handlebars.
I created two simple HTML templates for testing (using Handlebars) and filled them with content from an external JavaScript file. http://codepen.io/MaxVelichkin/pen/qNgxpB
Now I need content to lay initially in a JSON file.
I ran into two problems, but they both lie at the heart of solutions of the same main problem - creating a link between the content in the JSON file and HTML, so I decided to ask them in the same question.
How can I connect JSON and HTML? As far as I know there is a way, using AJAX, and there's a way that uses a server. AJAX is a new language for me, so I would be grateful for an explanation of how can I do it, using local HTTP server, that I created using Node.JS.
What should be the syntax in a JSON file? The script in the JSON file must be the same, as a script in JavaScript file, but then it should be processed with the help of JSON.parse function, is that correct? Or syntax in JSON file should be different?
For example, if we consider my example (link above), the code for the first template in the JSON file must be the same as in the JavaScript file, but before the last line document.getElementById('quoteData').innerHTML += quoteData;, I have to write the following line var contentJS = JSON.parse(quoteData);, and then change the name of the variable in the last line, so it will be: document.getElementById('quoteData').innerHTML += contentJS;, Is it right?
Try this:
HTML:
<!-- template-1 -->
<div id="testData"></div>
<script id="date-template" type="text/x-handlebars-template">
Date:<span> <b>{{date}}</b> </span> <br/> Time: <span><b>{{time}}</b></span>
</script>
JS:
function sendGet(callback) {
/* create an AJAX request using XMLHttpRequest*/
var xhr = new XMLHttpRequest();
/*reference json url taken from: http://www.jsontest.com/*/
/* Specify the type of request by using XMLHttpRequest "open",
here 'GET'(argument one) refers to request type
"http://date.jsontest.com/" (argument two) refers to JSON file location*/
xhr.open('GET', "http://date.jsontest.com/");
/*Using onload event handler you can check status of your request*/
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else {
alert(xhr.statusText);
}
};
/*Using onerror event handler you can check error state, if your request failed to get the data*/
xhr.onerror = function () {
alert("Network Error");
};
/*send the request to server*/
xhr.send();
}
//For template-1
var dateTemplate = document.getElementById("date-template").innerHTML;
var template = Handlebars.compile(dateTemplate);
sendGet(function (response) {
document.getElementById('testData').innerHTML += template(response);
})
JSON:
JSON data format derives from JavaScript, so its more look like JavaScript objects, Douglas Crockford originally specified the JSON format, check here.
JavaScript Object Notation has set of rules.
Starts with open curly braces ( { ) and ends with enclosing curly braces ( } )
ex: {}
Inside baces you can add 'key' and its 'value' like { "title" : "hello json"}
here "title" is key and "hello json" is value of that key.
"key" should be string
"value" can be:
number
string
Boolean
array
object
Can not add JavaScript comments inside JSON (like // or /**/)
there are many online JSON validators, you can check whether your JSON is valid or not, check here.
When comes to linking JSON to js file, its more like provide an interface to get JSON data and use it in your JavaScript.
here XMLHttpRequest our interface. we usually call XMLHttpRequest API.
In the given js code, to get JSON from the server using an REST API (http://date.jsontest.com/)
for more information on REST API you can check here
from the url: http://date.jsontest.com/ you can get JSON object like below.
{
"time": "03:47:36 PM",
"milliseconds_since_epoch": 1471794456318,
"date": "08-21-2016"
}
Note: data is dynamic; values change on each request.
So by using external API you can get JSON, to use it in your JavaScript file/ code base you need to convert JSON to JavaScript object, JSON.parse( /* your JSON object is here */ ) converts JSON to js Object
`var responseObject = JSON.parse(xhr.responseText)`
by using dot(.) or bracket ([]) notation you can access JavaScript Object properties or keys; like below.
console.log(responseObject.time) //"03:47:36 PM"
console.log(responseObject["time"]) //"03:47:36 PM"
console.log(responseObject.milliseconds_since_epoch) //1471794456318
console.log(responseObject["milliseconds_since_epoch"])//1471794456318
console.log(responseObject.date) //"08-21-2016"
console.log(responseObject["date"]) //"08-21-2016"
So to link local JSON file (from your local directory) or an external API in your JavaScript file you can use "XMLHttpRequest".
'sendGet' function updatedin the above js block with comments please check.
In simple way:
create XMLHttpRequest instance
ex: var xhr = new XMLHttpRequest();
open request type
ex: xhr.open('GET', "http://date.jsontest.com/");
send "GET" request to server
ex: xhr.send();
register load event handler to hold JSON object if response has status code 200.
ex: xhr.onload = function () {
for more info check here
Know about these:
Object literal notation
difference between primitive and non-primitive data types
Existing references:
What is JSON and why would I use it?
What are the differences between JSON and JavaScript object?
Basically, JSON is a structured format recently uses which would be preferred due to some advantages via developers, Like simpler and easier structure and etc. Ajax is not a language, It's a technique that you can simply send a request to an API service and update your view partially without reloading the entire page.
So you need to make a server-client architecture. In this case all your server-side responses would be sent in JSON format as RESTful API. Also you can simply use the JSON response without any conversion or something else like an array object in JavaScript.
You can see some examples here to figure out better: JSON example

how can I access to a specific json value in my returned data

I send a http GET request which returns JSON data in the following form. I am finding it impossible to access this data despite having no problems with example json that I create. I want to ideally take the array under wifi, and use this data to create a html table, but I think I can work out how to create the table if I could just access the actual elements of the data.
I have tried multiple methods to try and reach the first timestamp. I have tried:
var element = result.undefined.clients.wifi[0].timestamp;
but this returns an error that 'clients' can't be found.
I also tried:
var element = result.clients.wifi[0].timestamp; //and
var element = result.wifi[0].timestamp;
The JSON data returned to a variable is shown below:
result = undefined
{"sourceId":"idid","sourceType":"CLOUD_source","searchMeta":{"maxResults":4,"metricType":["clients"],"family":["wifi"],"Interval":"M1"},
"clients":{"wifi":
[{"timestamp":1424716920,"avg":3,"min":1,"max":4,"Count":8,"sCount":3,"sources":["x1","x2","x3","x4","x5","x6","x7","x8"]},{"timestamp":1424716980,"avg":2,"min":1,"max":3,"Count":4,"sCount":2,"sources":["x3","x4","x8","x4"]},{"timestamp":1424717160,"avg":2,"min":1,"max":3,"Count":9,"sCount":4,"sources":["x3","x4"]}]}}
The JSON data is invalid. If it is returned from a server, you need to go there and correct the data source, (if you have access to that).
Otherwise, perhaps notify the backend guy(s) about it.
If it is from a REST API, and you are "sure" that the server code should be error free, then check that you have supplied all the required parameters in the API request you are making.
I think your JSON is messed up. I ran it through JSONLint, and having the undefined at the beginning causes things to break.

JSON response from Google Analytics api

I am using the google-api-ruby-client to get a response from the Google Analytics api, which is successful, the one thing I am a little confused with though is the response object. I would like to know how to drill down into specific keys and their values or even parse the response to make it more understandable.
Below is what I believe is the relevant part of the JSON response
"{\"kind\":\"analytics#gaData\",\"id\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:88893966&dimensions=ga:pagePath&metrics=ga:pageviews&filters=ga:pagePath%3D%3D/&start-date=2014-01-01&end-date=2014-07-22\",\"query\":{\"start-date\":\"2014-01-01\",\"end-date\":\"2014-07-22\",\"ids\":\"ga:88893966\",\"dimensions\":\"ga:pagePath\",\"metrics\":[\"ga:pageviews\"],\"filters\":\"ga:pagePath==/\",\"start-index\":1,\"max-results\":1000},\"itemsPerPage\":1000,\"totalResults\":1,\"selfLink\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:88893966&dimensions=ga:pagePath&metrics=ga:pageviews&filters=ga:pagePath%3D%3D/&start-date=2014-01-01&end-date=2014-07-22\",\"profileInfo\":{\"profileId\":\"88893966\",\"accountId\":\"53082810\",\"webPropertyId\":\"UA-53082810-1\",\"internalWebPropertyId\":\"85713348\",\"profileName\":\"All Web Site Data\",\"tableId\":\"ga:88893966\"},\"containsSampledData\":false,\"columnHeaders\":[{\"name\":\"ga:pagePath\",\"columnType\":\"DIMENSION\",\"dataType\":\"STRING\"},{\"name\":\"ga:pageviews\",\"columnType\":\"METRIC\",\"dataType\":\"INTEGER\"}],\"totalsForAllResults\":{\"ga:pageviews\":\"8\"},\"rows\":[[\"/\",\"8\"]]}"
which is obtained from
# make queries
result = client.execute(:api_method => api_method, :parameters => {
'ids' => PROFILE,
'start-date' => Date.new(2014,1,1).to_s,
'end-date' => Date.today.to_s,
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:pageviews',
'filters' => 'ga:pagePath==/'
})
puts ap(result)
Also when I do:
puts ap(result.data.rows.inspect)
#returns
"[[\"/\", \"8\"]]"
and when i try
response = JSON.parse(result.data.totalsForAllResults)
puts ap(response)
# returns error
TypeError: no implicit conversion of #<Class:0x00000001950550> into String
I am wondering how I can format the response without the backslashes and how I would say get the total page views?
Your syntax is off.
If result is simply a string that is a json object, which it looks like above, what you want is:
response = JSON.parse(result)
ap response["totalsForAllResults"]["ga:pageviews"]
Looking at the google-api-ruby-client the result.data returns an object if parseable from api schema, a hash if you pass the media type "application/json", or a string otherwise. So you need to determine if you are accessing the response data as an object or a Hash. My example above parses the raw string into a ruby hash.
tl;dr; there are multiple ways to attain the data you want.
Yes, your syntax is off. It should look something like this.
https://www.googleapis.com/analytics/v3/data/ga?ids=ga:_____&dimensions=ga:date&metrics=ga:impressions,ga:adClicks,ga:adCost&start-date=2015-10-13&end-date=today
BaseUrl, id, metrics, start-date and end-date are required. And don't forget to insert the access_token as well.

How can I send foreign characters with YUI io (XMLHttpRequest)

I'm using YUI io to post data to my server. I have some problems sending foreign characters like æ ø å.
First case: a form is posted to the server
Y.io(url, {
method: 'POST',
form: {
id: 'myform',
useDisabled: true
}
});
This will post the content of the form to the server. If I have a field named "test1" containing "æøå", then on the server I'll see REQUEST_CONTENT="test1=%C3%A6%C3%B8%C3%A5". This can be easily decode with a urldecode function, NO PROBLEM, but...
Second case: data is posted this way:
Y.io(uri, {
data : '{"test1":"æøå"}'),
method : "POST"
});
Now I see this on the server REQUEST_CONTENT="{"test1":"├ª├©├Ñ"}". How can I decode that? And why is it send like that?
I know I can use encodeURIComponent() to encode the string before sending it. But the io request is actually part of a Model Sync operation, so I'm not calling io directly. I'm doing something like this:
Y.User = Y.Base.create('user', Y.Model, [Y.ModelSync.REST], {....});
var user = new Y.User();
user.set('test1', 'æøå');
user.save();
So it doesn't make sense to encode/decode everytime I set/read the attribute.
Also I have tried to set charset=utf-8 in the request header, but that didn't change anything.
EDIT
I have done some more debugging in chrome and the request is created with this line of code:
transaction.c.send(data);
transaction.c is the xmlhttprequest and (using chrome debugger) I can see the data is "{"test1":"æøå"}"
When the above line of code is executed, a pending network entry is shown (under the network tab in chrome debugger). Request payload displays {"test1":"├ª├©├Ñ"}
Headers are:
Accept:application/json
Content-Type:application/json; charset=UTF-8
ModelSync.REST has a serialize method that decides how the data in the model is turned into a string before passing it to Y.io. By default it uses JSON.stringify() which returns what you're seeing. You can decode it in the server using JSON. By your mention of urldecode I guess you're using PHP in the server. In that case you can use json_decode which will give you an associative array. If I'm not mistaken (I haven't used PHP in a while), it should go something like this:
$data = json_decode($HTTP_RAW_POST_DATA, true);
/*
array(1) {
["test1"] => "æøå"
}
*/
Another option would be for you to override the serialize method in your User model. serialize is a method used by ModelSync.REST to turn the data into a string before sending it through IO. You can replace it with a method that turns the data in the model into a regular query string using the querystring module:
Y.User = Y.Base.create('user', Y.Model, [Y.ModelSync.REST], {
serialize: function () {
return Y.QueryString.stringify(this.toJSON());
}
});
Finally, ModelSync.REST assumes you'll be using JSON so you need to delete the default header so that IO uses plain text. You should add this at some point in your code:
delete Y.ModelSync.REST.HTTP_HEADERS['Content-Type'];

Categories