calling window.sessionStorage in node js - node.js

How do I call window.sessionStorage in node js to get values of keys stored in the browser?
Is there an npm module that will allow me to store values in session storage?

You cannot get it directly, but you can send them from browser to node using for example ajax.
var sessionData = {};
for(var i = 0; i < window.sessionStorage.length; i++) {
var key = window.sessionStorage.key(i);
sessionData[key] = window.sessionStorage.getItem(key);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://node_server_url/', true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(sessionData));
Now you just need to receive and parse this data using JSON.parse()

Related

Access Azure Data Explorer with Kusto.Data in Azure Function -- Kusto failed to send request -- local debugging works

I am having the following problem and an extensive search online didn't provide any good results.
When trying to access my Azure Data Explorer Database and querying using the Kusto.Data SDK in an Azure Function, it yields the following error:
Kusto client failed to send a request to the service: 'An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call.'
However, running the Function on my local machine, everything works fine.
Edit: The function excepts at using (var reader = await queryProvider.ExecuteQueryAsync(Database, query, clientRequestProperties))
EDIT2 - SOLUTION:
You can downgrade the NuGet Kusto.Data Package to Version 9.4.1, this solves the problem and doesn't throw any error anymore. If you still encounter difficulties, you can try to directly access the ADX database via http requests:
const string tenantId = "<tenantId>";
const string client_id = "<clientId>";
const string client_secret = "<client_secret>";
const string Cluster = "<cluster_adress";
const string Database = "<database_name>";
var authUrl = "https://login.microsoftonline.com/<tenantId>/oauth2/token";
var param = new Dictionary<string, string>
{
{"client_id",client_id},
{"grant_type","client_credentials"},
{"client_secret",client_secret},
{"resource","https://help.kusto.windows.net"}
};
var data = new FormUrlEncodedContent(param);
using var authClient = new HttpClient();
var response = await authClient.PostAsync(authUrl, data);
string result = response.Content.ReadAsStringAsync().Result;
//parse result
var resultJson = System.Text.Json.JsonDocument.Parse(result);
//retrieve access token
var accessToken = resultJson.RootElement.GetProperty("access_token");
//-----------------------------------------------------------------------------------------------
var dataXUrl = Cluster + "/v1/rest/query";
var database = Database;
var dataXQuery = "sample_table| where Time > ago(2min)";
var body = new Dictionary<string, string>
{
{"db",database},
{"csl",dataXQuery}
};
using var dataXClient = new HttpClient();
dataXClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.ToString());
dataXClient.DefaultRequestHeaders.Add("Accept", "application/json");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, dataXUrl);
request.Content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
var table = await dataXClient.SendAsync(request);
//pretty print
var obj = JsonConvert.DeserializeObject(table.Content.ReadAsStringAsync());
var tableJSON = JsonConvert.SerializeObject(obj, Formatting.Indented);
log.LogInformation("\n\n" + tableJSON);
I am having the same issue on a continuous webjob on an Azure App Service. The Kusto nuget version I am using is 10.1.0
Downgrading to nuget 9.4.1 solved the problem immediately.
FYI - This only seems to affect 10.1.0. The earlier 10.x.x versions should work.
The ADX team believes they will have this fixed in the next nuget version.

Can not get token for TextToSpeechAPI

Here is the code:
private AccessTokenInfo GetToken()
{
WebRequest webRequest = WebRequest.Create("https://oxford-speech.cloudapp.net/token/issueToken");
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(_requestDetails);
webRequest.ContentLength = bytes.Length;
try
{
using (Stream outputStream = webRequest.GetRequestStream())
{
outputStream.Write(bytes, 0, bytes.Length);
}
// ...
I have got the exception:
the underlying connection was closed could not establish trust relationship
How can I fit it ?
I hope I'm not missing something here...
The URL you're using isn't the one that generates tokens for the Text-to-Speech API as documented here. (The "Oxford" that's referenced in your URL refers to the Project Oxford which Cognitive Services was formerly known as.)
Also, WebRequest is deprecated. Use the System.Net.Http package instead.
The code to invoke the new REST endpoint then would look something like:
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Post, "https://api.cognitive.microsoft.com/sts/v1.0/issueToken"))
{
request.Headers.Add("Ocp-Apim-Subscription-Key", "YOUR-KEY-HERE");
var response = await client.SendAsync(req);
var token = await response.Content.ReadAsStringAsync();
}
Finally, there are several client libraries that may get you around from writing any code to hit the REST services at all.

Embed an instagram feed

I am looking to simply add a instagram feed onto a cms website - I have got an api code/secret key to use - but the instagram instructions make absolutely no sense. I can see how to embed one post - but not an entire feed (i am not a developer so I donlt understand how to write a get/ombed query - but if I had a code snipper I could change it!)
I just need the code as I presume I can then change this to the relevant instragram account
https://www.instagram.com/developer/embedding/
Here is a link to a good post about how to display an Instagram feed on your website. Parts of the article include javascript, but the author tries to keep it as simple as possible. The main javascript code is:
var request = new XMLHttpRequest();
request.open('GET', 'https://api.instagram.com/v1/users/self/media/recent/?access_token=ENTER-YOUR-ACCESS-TOKEN-HERE&count=8', true);
request.onload = function(container) {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
for (var i=0;i < data.data.length;i++) {
var container = document.getElementById('insta-feed');
var imgURL = data.data[i].images.standard_resolution.url;
console.log(imgURL);
var div = document.createElement('div');
div.setAttribute('class','instapic');
container.appendChild(div);
var img = document.createElement('img');
img.setAttribute('src',imgURL)
div.appendChild(img);
}
console.log(data);
} else { }
};
request.onerror = function() {
//There was a connection error of some sort
};
request.send();
This code adds the instagram image to the html div with the id "insta-feed". So you need to add the following html to your page:
<div id="insta-feed"></div>
A similar piece of code using jquery would be:
$.get("https://api.instagram.com/v1/users/self/media/recent/?access_token=ENTER-YOUR-ACCESS-TOKEN-HERE&count=8", function (result) {
var html = "";
for (var i = 0; i < result.data.length; i++) {
html += "<div><img src='" + result.data[i].images.standard_resolution.url + "' /></div>";
}
$("#insta-feed").html(html);
});

HTTP Request from plugin - One or more erros occured

I have been trying to make a HTTP POST request from plugin without lucky.
I have the same code working fine in my console appication however in plugin I get the following error: "One or more erros occured". I tried to run it asynchronously but it did not work as well.
I really appreciate any idea, thank you!
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "KEY");
// Request parameters
queryString["chave"] = "key2";
queryString["codigo_obra"] = codigoObra;
queryString["codigo_bloco"] = codigoBloco;
queryString["codigo_unidade"] = codigoUnidade;
queryString["codigo_planta"] = codigoPlanta;
var uri = "http://test?" + queryString;
HttpResponseMessage response;
// Request body
byte[] byteData = Encoding.UTF8.GetBytes("");
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
//This line gives me the error.
response = client.PostAsync(uri, content).Result;
}

Using HttpClient to upload files to ServiceStack server

I can't use the ServiceStack Client libraries and I've chosen to use the HttpClient PCL library instead. I can do all my Rest calls (and other json calls) without a problem, but I'm now stucked with uploading files.
A snippet of what I am trying to do:
var message = new HttpRequestMessage(restRequest.Method, restRequest.GetResourceUri(BaseUrl));
var content = new MultipartFormDataContent();
foreach (var file in files)
{
byte[] data;
bool success = CxFileStorage.TryReadBinaryFile(file, out data);
if (success)
{
var byteContent = new ByteArrayContent(data);
byteContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = System.IO.Path.GetFileName(file) ,
};
content.Add(byteContent);
}
}
message.Content = content;
Problem is now that I get a null reference exception (status 500) when posting. I doesn't get into the service. I see the call in the filterrequest, but that's it.
So I'm wondering what I do wrong and how I can pinpoint what is going wrong. How can I catch the correct error on the ServiceStack layer?

Resources