XHR to non-ssl IP - xmlhttprequest

I would like to create a Javascript XHR request to a local IP of an Epson TM88V Printer. The site has a SSL certificate so we've to make a secured connection. Unfortunately, it is not possible to upload a certificate in the printer.
Is it possible to add a certificate in the XHR request or is there another way to create a secured connection?
Below the print code without SSL.
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://192.168.1.168/cgi-bin/epos/service.cgi?devid=local_printer', true);
xhr.timeout = 5000;
xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status != 200) {
callback({ success: false, data: data });
} else if (xhr.readyState == 4) {
callback({ success: true, data: data });
}
}
xhr.send('<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><epos-print xmlns="http://www.epson-pos.com/schemas/2011/03/epos-print">Test print</epos-print></s:Body></s:Envelope>');

Related

https clientside and http back end cookie is not sent

I am new to web development. At first, I created an authentication system with http protocol for both client dev-server and backend dev-server, which worked properly. However, I had to make the client dev-server secure to implement HLS video player. Therefore, now client side url is (https://localhost:15173/login), and backend url (http://localhost:3000). When client side url is (http://localhost:15173/login), cookie was generated on server-side and sent to the client side. So, I would like to know why this is happening.
Serverside: nodejs, express.js
Client side: javascript, vue3.js
Do I have to make both client side and backend https?
Here is backend code to generate cookie:
res.cookie('JWTcookie', accessToken, { httpOnly: true})
res.status(200).json(responseJson)
Here is backend code to validate cookie:
app.get("/login", function (req, res) {
var JWTcookie = req.cookies.JWTcookie;
console.log("JWT cookie is here", req.cookies.JWTcookie);
try {
console.log("veryfy token is here", verifyToken(JWTcookie));
const decoded = jwt.verify(JWTcookie, SECRET_KEY, function (err, decoded) {
return decoded;
})
const responseJson = {
success: true,
username: decoded.name,
userID: decoded.id
}
res.status(200).json(responseJson);
// console.log("decoded token ", decoded);
}
catch (err) {
const status = 401
const message = 'Unauthorized'
res.send("Not authorized. Better login");
// res.status(status).json({ status, message })
}
});
Here is client side code (vue.js) to send cookie to the sererside:
onMounted(() => {
const API_URL = "http://localhost:3000/";
const authStore = userAuthStore();
axios.get(API_URL + "login", { withCredentials: true }).then(res => {
if (res.data.success == true) {
const id = res.data.userID;
const username = res.data.username;
authStore.auth();
authStore.setUser(id, username);
console.log("mounted.")
router.push("/video");
}
else {
console.log("Response is here: ", res.data)
}
})
})
I believe the problem is the lack of understanding of how security system work when one of them is https and the other is http.
Any help would be appreciated. Thank you.
I tried to make the cookie secure by adding:
res.cookie('JWTcookie', accessToken, { httpOnly: true, secure: true})
But this didn't work.
When I gave both server side and client side https, it worked.

Shutdown Kodi with api (blackberry qml)

Hello I trying shutdown Kodi (raspberry pi) with mobile app (blackberry qml).
But I do not how.
I used this code: (in browser)
"http://[myip]:[myport]/jsonrpc?request={"jsonrpc":"2.0","method":"System.Suspend","id":1}"
I used this code: (in the app)
function sendRequest() {
var xhr = new XMLHttpRequest();
var url = "http://[myip]:[myport]/jsonrpc?request={\"jsonrpc\":\"2.0\",\"method\": \"System.Suspend\",\"id\":1}"
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log(xhr.responseText);
textArea.text = xhr.responseText;
}
}
};
xhr.open("GET", url, true); // with "POST" I got the same problem.
xhr.send();
}
I got:
{"error":{"code":-32700,"message":"Parse error."},"id":null,"jsonrpc":"2.0"}
Remote from web browser works fine (http://[myip]:[myport])
Thank you for your answers.
********** Update: 21.10.2020 **********
I'm in progress. But I don't know what to do next.
I found some information why I have an error.
I don't know how to implement in my code.
Can you help me?
Thank you so much.
https://github.com/xbmc/xbmc/pull/12281
https://forum.kodi.tv/showthread.php?tid=324598&highlight=json
Here's how to do it.But I can't understand it.
https://retifrav.github.io/blog/2018/09/01/kodi-remote-control-app/
This is my function (on Kodi 17.6 it is working but on Kodi 18 is not working )
function sendRequest() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
text.text = xhr.responseText
}
}
};
var url = 'http://<IP:PORT>/jsonrpc?request={"jsonrpc": "2.0", "id": 1, "method": "System.Shutdown"}'
xhr.open("GET", url, true) // when I write "POST" - nothing happens
xhr.send()
}
You should URL encode the json in your url before it's used in the open method. Use encodeURIComponent() to do that. Your browser is changing:
{"jsonrpc":"2.0","method": "System.Suspend","id":1}"
To:
%7B%22jsonrpc%22%3A%222.0%22%2C%22method%22%3A%20%22System.Suspend%22%2C%22id%22%3A1%7D%22
But your code is not.

Xhttp request always returns a 0 response code. - While making a post request using form data

I am trying to upload an array of images using form data and xhttp.
Client : React Native - Both platforms
Server : Node running on GCP
Images go into s3.
Problem : Images are uploaded into s3. And when i look at my server logs i see the server is sending 200.
But, client is always receiving response code 0.
And also xhttp goes from state 1 -> 4.
We have added CORS on both ends so that might not be an issue.
I have accept and content headers. But, no idea what's going wrong.
Any help is appreciated.
React-Native Client:
upload()
{
let url = "MYAPIGOESHERE"
let uploadBody = new FormData()
let imagesUpload = []
imagesUpload.push({type:'image/jpg',uri:this.state.coverImage[0].uri,name:"cover"})
uploadBody.append('photos',{uri:this.state.coverImage[0].uri, type:'image/jpg', name:"cover"})
uploadBody.append('duration',this.state.duration)
var xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function() {
console.log(this.readyState+" "+this.statusText)
if (this.readyState === 4) {
alert(this.status)
if (this.status === 200) {
console.log(this.responseText);
} else {
console.log(this);
}
}
if(this.readyState === 3)
{
console.log("Inside 3")
}
if(this.readyState === 2)
{
console.log("Inside 2")
}
};
xhttp.open("POST", url)
xhttp.setRequestHeader('Accept', 'application/json');
xhttp.setRequestHeader('Access-Control-Allow-Origin', '*');
xhttp.responseType = 'json'
xhttp.send(uploadBody)
}

ICE failed, PeerJS call started but no video/audio through

I am trying to get a simple video chat working with PeerJS. I want to send audio between Firefox on a pc and Firefox on Android. I can get the call running (call.on) and I can view local video but for some reason the media just doesn't come through to the other user. Currently I am getting the error:
ICE failed, see about:webrtc for more details
I have a server which in its simple version is as such:
var ip = require('ip');
var PeerServer = require('peer').PeerServer;
var port = 9000;
var server = new PeerServer({port: port, allow_discovery: true});
Then I have two clients, one for the pc that makes the call:
var SERVER_IP = window.location.hostname;
var SERVER_PORT = 9000;
var localStream = "";
var peerID = "pc"
var peerConnectionID = "and"
var remoteVideo = document.querySelector('#rremote-video');
var localVideo = document.querySelector('#llocal-video');
var peer = new Peer(peerID, {host: SERVER_IP, port: SERVER_PORT});
var conn = peer.connect(peerConnectionID);
var getUserMedia = navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(stream => localVideo.srcObject = stream)
.then(stream => localStream = stream)
.catch(e => console.log(e.name + ": "+ e.message));
waitForElement();
function waitForElement(){
if(localStream != ""){
conn.on('open', function(){
conn.send('hi from PC!');
});
peer.on('connection', function(conn) {
conn.on('data', function(data){
console.log(data);
});
});
console.log("we have a stream: "+localStream);
var call = peer.call(peerConnectionID, localStream);
console.log("Calling "+peerConnectionID);
call.on('stream', function(remotestream) {
console.log("Call on.");
remoteVideo.srcObject = remotestream;
});
}
else{
setTimeout(function(){
waitForElement();
},750);
}
}
And the one that answers the call is:
var SERVER_IP = window.location.hostname;
var SERVER_PORT = 9000;
var localStream = "";
var peerID = "and"
var peerConnectionID = "pc"
var remoteVideo = document.querySelector('#rremote-video');
var localVideo = document.querySelector('#llocal-video');
var remoteAudio = document.querySelector('#remote-audio');
var localAudio = document.querySelector('#local-audio');
var peer = new Peer(peerID, {host: SERVER_IP, port: SERVER_PORT});
var conn = peer.connect(peerConnectionID);
var getUserMedia = navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(stream => localAudio.srcObject = stream)
.then(stream => localVideo.srcObject = stream)
.then(stream => localStream = stream)
.catch(e => console.log(e.name + ": "+ e.message));
waitForElement();
function waitForElement(){
if(localStream != ""){
conn.on('open', function(){
conn.send('hi from android!');
});
peer.on('connection', function(conn) {
conn.on('data', function(data){
console.log(data);
});
});
peer.on('call', function(call) {
console.log("Picking up call.");
call.answer(localStream);
call.on('stream', function(remotestream) {
console.log("Call on.");
remoteVideo.srcObject = remotestream;
});
});
}
else{
setTimeout(function(){
waitForElement();
},750);
}
}
I think it is some little tweak that I'm getting wrong, I have mainly followed instructions on PeerJS website: http://peerjs.com/ Please if anyone can see something that needs to change, any help is welcome!
Are you using https? Making calls to non-local machines is no longer allowed by the browsers.
To test this out, run both sets of code on your local machine. If you can do that connection, it means your code is ok.
To do a remote connection you will unfortunately need https. This means you will also need your own peerjs server (to run as https).
The other option is to use port forwarding to make one of the machines think it is talking to the localhost
It sounds like your ICE Candidates cannot communicate one to each other. You will have to use a STUN server and, if it still doesnt work, you will need a TURN server.
From PeerJS Documentation:
var peer = new Peer({
config: {'iceServers': [
{ url: 'stun:stun.l.google.com:19302' },
{ url: 'turn:homeo#turn.bistri.com:80', credential: 'homeo' }
]} /* Sample servers, please use appropriate ones */
});
This link will provide you a method to deploy your own TURN server.

xmlhttprequest in chrome extension

I am developing a chrome extension and I have an iframe which I use in my extension. This is what I do with my iframe
"When I drag and drop a image to my iframe I handle the drop event in one of the content scripts and pass that function call my extension code. There I create a xmlhttprequest object and then send the URL of the image to a php file in my server."
This is what is happening. I get a readyState of "4" but there is no POST request going out of my browser. I checked with the "NETWORK" tab in the browser but there is no POST request going out of the browser (I have listed my site in the permissions section of the manifest file).
This is my code --.>
JScript.js(One of the content scripts )
drop: function(event, ui) {
var imgurl=$(ui.draggable).attr('src');
imgurl="IMGURL="+imgurl;
_post("www.somedomain.come/testing.php",imgurl,function(result){ alert("success")});
}
This is my proxy in the same content script-->
_post = function(url, data, callback)
{
console.log("sending post");
chrome.extension.sendRequest({
msgType:'post',
data: data,
url:url
}, function(response){
alert(response);
});
}
This my OnRequest function handler in background.html -->
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
if (request.msgType === 'post') {
alert("Now in OnRequest function");
// console.log("Now in Onrequest Function");
alert("Url: "+request.url + "\n Data : "+ request.data);
ajaxcallingfunction(request);
alert("completed the ajax call");
sendResponse("success");
}
});
var ajaxcallingfunction = function(request){
var xhr = new XMLHttpRequest();
xhr.open("POST",request.url, false);
xhr.onreadystatechange = function(){
alert(xhr.readyState);
if (xhr.readyState == 4) {
alert(xhr.readyState);
}
}
xhr.send(request.data);
alert("after xhr call");
};
You have http:// in front of your url, right?
xhr.readyState doesn't tell much, it just means that it is done. Check out what's inside xhr.status, it would contain error code. If everything is ok it should be 200:
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
alert(xhr.status);
}
}