Deserialize data from websocket response - javascript

I'm am trying to deserialize a WebSocket response with the package msgpacket.
When trying to deserialize the packet response I am getting the error:
Uncaught Error: Invalid argument: The byte array to deserialize is empty.
Here is a basic snippet showing this. I am using echo.websocket.org to test this. It sends back the same response it gets.
this.socket = new WebSocket('wss://echo.websocket.org');
this.socket.onopen = () => {
console.log('connected');
var sourceData = {
hello: 1,
world: "test"
};
var data = msgpack.serialize(sourceData);
this.socket.send(data.buffer);
var after = msgpack.deserialize(data.buffer);
console.log(after);
}
this.socket.onmessage = function (event) {
var data = msgpack.deserialize(new Uint8Array(event.data));
console.log(data);
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="https://raw.githack.com/ygoe/msgpack.js/master/msgpack.min.js"></script>
</body>
</html>
I am simply trying to retrieve the data after receiving the WebSocket response.

I was able to solve the problem.
I figured out I needed to convert a blob into an array buffer
This is what worked
var blob = event.data;
var arrayBuffer = null;
arrayBuffer = await new Response(blob).arrayBuffer();
var data = msgpack.deserialize(arrayBuffer);
console.log(data);
Found here: https://stackoverflow.com/a/55204517/10997917

Related

Why does httpr.send() always fail?

I had similar code run before but now i've lost it. No matter what I do, it will never run the php code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function kosarica() {
var vrednost = "Itworks!";
var httpr=new XMLHttpRequest();
httpr.open("POST","izpis3.php",true);
httpr.setRequestHeader("Content-type","aplication/x-www-form-urlencode");
httpr.onreadystatechange=function(){
if(httpr.readyState==4 && httpr.status ==200){
document.getElementById("responce").innerHTML=httpr.responseText;
}
httpr.send("vrednost"+vrednost);
}
}
</script>
</head>
<body>
<p id="responce">a</p>
<button onclick="kosarica()">Click me</button>
</body>
</html>
PHP Code:
<?php
echo $_POST['vrednost'];
?>
I know that I can make code for this example all in javascript but I want to run more php code where it access my database.
It does not fail, but it does never happen. You need to move the send() outside the handler.
The content type is wrong.
You need to use an equal sign to make it a variable for PHP.
Please do not use var keyword. Use const for a constant or let for a variable.
function kosarica() {
const vrednost = "Itworks!";
const httpr = new XMLHttpRequest();
httpr.open("POST", "izpis3.php", true);
httpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpr.onreadystatechange = function () {
if (httpr.readyState === 4 && httpr.status === 200) {
document.getElementById("responce").innerHTML = httpr.responseText;
}
}
httpr.send("vrednost=" + vrednost);
}

LinkedIn Learning LTI failed authentication

I'm attempting to integrate LinkedIn Learning Single-Sign-On via an LTI connection, however I'm always faced with the response: LTI_FAILED_AUTHENTICATION.
LinkedIn Learning - LTI_FAILED_AUTHENTICATION
When I test it out on the Saltire test platform, it strangely works.
The parameters match what I am sending from the code below:
Saltire LTI Success authentication
Have tried copying over the the values of oauth_nonce, timestamp and oauth_signature from Saltire to my page, and that worked also, which scores out the possibility of domain whitelisting requirement.
LinkedIn support have come back saying there seems to be something wrong with the generated signature, but I'm not sure what is wrong about it, since that is generated by the parameters passed.
Is there something incorrectly setup from my page which I am not seeing?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="robots" content="noindex" />
<title>Access LinkedIn Learning</title>
<script src="bundle.js"></script>
</head>
<body>
<form id="id_frmConnect" name="frmConnect" enctype="application/x-www-form-urlencoded">
</form>
<script>
var oauth = require('oauth-sign');
var action = 'https://www.linkedin.com/checkpoint/enterprise/login/[accountID]?application=learning&redirect=https://www.linkedin.com/learning/me';
var method = 'POST';
var consumer_key = '************';
var consumer_secret = '************';
var timestamp = Math.round(Date.now() / 1000);
var params = {
lti_message_type: 'basic-lti-launch-request',
lti_version: 'LTI-1p0',
oauth_callback: 'about:blank',
oauth_consumer_key: consumer_key,
oauth_nonce: btoa(timestamp),
oauth_signature_method: 'HMAC-SHA1',
oauth_timestamp: timestamp,
oauth_version: '1.0',
user_id: 'S495696'
};
var signature = oauth.hmacsign(method, action, params, consumer_secret);
params.oauth_signature = signature;
var form = document.querySelector("#id_frmConnect");
form.action = action;
form.method = method;
for (var name in params) {
var node = document.createElement("input");
node.type = 'hidden';
node.name = name;
node.value = params[name];
form.appendChild(node);
}
</script>
</body>
</html>
I figured out the issue. By using the Saltire test tool, I was able to verify that my signature was generated correctly when using their testing URL: https://lti.tools/saltire/tp
You can play with an example here: https://learningcom.github.io/ltitest/index.html
So after looking at the LinkedIn URL, I discovered that the signature was getting generated with an unnecessary long URL which contained parameters.
Removed: ?application=learning&redirect=https://www.linkedin.com/learning/me
Therefore, I shortened the URL to:
var action = 'https://www.linkedin.com/checkpoint/enterprise/login/[accountID]';
No more errors!

How can I POST data from javascript to a c sharp back-end, and then receive it back?

So, I am fairly new to C Sharp and I can't figure out how I can basically submit a POST request via javascript (in the front-end) using fetch, send it to a C Sharp back-end to process the data, and then receive it back to my site.
My final goal is to achieve a search engine, where I can get user input from javascript and send it to my C Sharp back-end so I can crawl sites from a database and return the ones which contain the highest volume of the key-word.
Here is what I am currently working within the front-end:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./index.css">
<title>Search Engine</title>
</head>
<body>
<form class="search">
<h2>Search Engine</h2>
<input name="search" type='text' placeholder='Search' />
<button type="submit">Submit</button>
</form>
<script>
const endpoint = "file to send data to";
const formEl = document.querySelector('form');
formEl.addEventListener('submit', async(e) => {
e.preventDefault();
const formData = new FormData(formEl);
const formDataSerialized = Object.fromEntries(formData);
try {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(formDataSerialized),
headers: {
'Content-Type': 'application/json'
}
});
const json = await response.json();
console.log(json);
} catch(e) {
console.error(e);
alert('there was an error!');
}
})
</script>
</body>
</html>
As you can see, I have a basic form that submits a user search, however, the endpoint in my javascript function is currently empty, since I am not sending the data anywhere.
I was looking around for a long while for a solution where I can make a web server with C Sharp and accept the data that way, however didn't find anything which I can use.
Can anyone please help? I would appreciate it a lot.

Manage Rcon remote web rust server

I am trying to develop a web application that allows me to type commands in the Rcon console via the web Browser.
The problem is that every time I send a command I get “[Rcon] Failed to parse message, incorrect format”.
Error message rcon
File log server
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket</title>
</head>
<body>
<h1>WebSockets Rust Server</h1>
<input type="button" value="Send" onclick="webSocketTest();">
<script>
function webSocketTest() {
// Create the WebSocket
const rcon = new WebSocket('ws://localhost:28016/1234');
rcon.onopen = function(e) {
// This line causes the problem
rcon.send('status');
}
rcon.onmessage = function(e) {
// Code
}
rcon.onerror = function(e) {
// Code
}
rcon.onclose = function(e) {
// Code
}
}
</script>
</body>
</html>
EDIT:
Finally I fix the problem. I was making the mistake of trying to collect the data in the wrong function.
<<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket</title>
</head>
<body>
<h1>WebSockets Rust Server</h1>
<input type="button" value="Send" id="btnSend"><br>
<textarea id="response" rows="10" cols="60"></textarea>
<script>
const rcon = new WebSocket('ws://localhost:28016/1234');
console.log(rcon);
rcon.onopen = function() {
console.log('Connected');
};
/* In this funcion have the server response */
rcon.onmessage = function(e) {
const msg = JSON.parse(e.data);
document.getElementById('response').innerHTML = msg.Message;
}
rcon.onerror = function (e) {
console.log(e);
}
rcon.onclose = function(e) {
console.log('Connection closed');
console.log(e);
};
/* Click Event on send btn that calls anonymous function to send the data */
const btnSend = document.getElementById("btnSend");
btnSend.addEventListener('click', function() {
/* Data to send */
const data = {
Message: "status", // rcon command
Identifier: 1, // +server.identity
Name: "totalgamer" // +server.hostname
};
/* Need to use JSON.stringify before send the data */
rcon.send(JSON.stringify(data));
});
</script>
</body>
</html>
Now it's works fine.

How to test sending form data through Javascript locally?

I'm learning about sending forms through JavaScript by manually building XMLHttpRequest.
In the end of given example, there's a note:
Note: This use of XMLHttpRequest is subject to the same-origin policy if you want to send data to a third party web site. For cross-origin requests, you'll need CORS and HTTP access control.
I'd like to test the example locally, though. What can I change to make it work locally? The address of posting request?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>Click me!</button>
<script>
function sendData(data) {
console.log('Sending data');
const XHR = new XMLHttpRequest();
let urlEncodedData = "",
urlEncodedDataPairs = [],
name;
for (name in data) {
urlEncodedDataPairs.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
}
urlEncodedData = urlEncodedDataPairs.join('&').replace('/%20/g', '+');
XHR.addEventListener('load', function (event) {
alert('Yeah! Data sent and response loaded.');
});
XHR.addEventListener('error', function (event) {
alert('Oops! Something went wrong.');
});
XHR.open('POST', 'https://example.com/cors.php');
XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XHR.send(urlEncodedData);
}
const btn = document.querySelector('button');
btn.addEventListener('click', function () {
sendData({ test: 'ok' });
})
</script>
</body>
</html>
You can use a fake REST API service, like https://reqres.in. Basic usage is free and requires no registration whatsoever.
They usually send back fake data and don't require CORS.
You just need to change the URL to https://reqres.in/api/users for example.

Categories