Running JavaScript with a web request? - javascript

BACK STORY :
Let me come from my problem, I need to update firebase database with Arduino so I used firebase-Arduino library but for some reason it will not compile Node MCU so my next way is a bit complicated that is I created a java script to update the firebase I just need to add 1 to the database so I don't need to update sensor value or anything so if I load the webpage it will update the value ,I thought it will be triggered with http request from Arduino but I was wrong it does not work like that.
QUESTION : How to run the JavaScript in a webpage with a web request from Arduino?

Assuming you have node.js installed you can have something like this (source):
const https = require('https');
https.get('your_url_here', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(JSON.parse(data).explanation);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
But if you don't have installed node.js you might create the http request from bash commands like curl. This can be useful since you can make it run as daemon (run on th background every X minutes).
Let me know if you managed, something good luck.

Related

How to connect to a TCP server and pass a Javascript to it

I'm definitely a newbie with JS and node. I have telescope management software called SkyX Pro, and it has the ability to run a TCP Server on port 3040. I can connect to it using Netcat and hand it a Javascript starting with //* Javascript *// this works and allows me to startup cameras and other equipment and send commands for taking pictures etc. The issue is it needs to be run from a batch file which makes getting any information back to an HTML page tough (Like Camera, focuser and filter wheel status and temperatures).
The NC call looks like "NC localhost 3040 < Javascript-file.js
To get around the browser to local machine security issues I want to run this from node.js with maybe socket.io-client if possible, but I don't know the proper syntax for it.
I have seen plenty of client syntax sending hello's etc. but nothing send javascript and allowing for two-way connectivity that I can understand.
I have tried using:
var socket = io.connect('http://localhost');`enter code here`
socket.on('httpServer', function (data) {
console.log(data);
document.write(data + "\r\n");
socket.emit('tcp', "For TCP");
});
const net = require('net');
const client = new net.Socket();
client.connect({ port: 3040, host: process.argv[2] });
client.on('data', (data) => {
console.log(data.toString('utf-8'));
But I do not understand it well enough to troubleshoot why it's not working.
Any help would be wonderful, and please treat me like a baby that needs its step by step.
Cheer
Peter
Reading [1], We can assume socket-io isn't the perfect fit for you, because that Server you have sound like a typical tcp-socket server, not a socket.io server ( which requires special headers ) or a web-socket server.
So you only needs "net" library to do the job.
const net = require('net');
// module to send a message to TCP-socket server and wait for the response from socket-server
const sendAndReceive = async (client, message) => {
client.write(message);
let response = null
await ( new Promise( (resolve, reject) => {
client.on('data', function(data) {
response = data;
resolve()
});
}))
return response;
}
// send a single message to the socket-server and print the response
const sendJSCode = (message) => {
// create socket-client
const client = new net.Socket();
client.connect(3040, 'localhost', async function() {
console.log('Connected');
// send message and receive response
const response = await sendAndReceive(client, message)
// parse and print repsonse string
const stringifiedResponse = Buffer.from(response).toString()
console.log('from server: ', stringifiedResponse)
// clean up connection
client.destroy()
});
}
sendJSCode('var Out; \n Out="TheSky Build=" + Application.build \n\r')
This script will:
Initiate a socket client
on connection successfully, client sends a message
client receives back response from that message
client prints response to terminal
Note that TheSkyX has a limitation of 4096 bytes for each message[2], any more than that and we will need to chunk the message. So you may want to keep the js-code short and precise.
that snippet I gave is minimal, it doesn't handle errors from server. If you want, you can add client.on("error", .. ) to handle it.
Your point of connecting to the socket server directly from browser is very intriguing, unfortunately it is not allowed by modern browsers natively due to security concerns 3
[1] https://socket.io/docs/#What-Socket-IO-is-not:~:text=That%20is%20why%20a%20WebSocket%20client,to%20a%20plain%20WebSocket%20server%20either.
[2] https://www.bisque.com/wp-content/scripttheskyx/scriptOverSocket.html#MSearchField:~:text=set%20to%204096%20bytes

Avoid 'Remote request only' error Message when Node Server access domain

Using Node.js, I am trying to send a GET request to server and I've used the following code for that.
const https = require('https');
https.get('https://example-domain-name/', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(data);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
The problem is that, the server is responding statusCode 500 (Runtime error).
An application error occurred on the server. The current custom error
settings for this application prevent the details of the application
error from being viewed remotely (for security reasons). It could,
however, be viewed by browsers running on the local server machine.
But browser is displaying the page normally, but using node js request, i get the something following response data(text).
How to avoid this and normally request and response data like browser using node.js?
Please Help... StackOverFlow is only my basis of help now!!

Struggling to perform a "simple" HTTP GET using Node.js - Destination Server Using TLS 1.0

I'm struggling to perform a "simple" HTTP GET using Node.js
I've done some digging, and I feel the error may stem from the Server Using TLS 1.0?
Below is a simple block of code to replicate the issue.
I'm using Node v10.9.0
const https = require('https');
https.get('https://supplychain.2go.com.ph', (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
console.log(data);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
The error returned is:
Client network socket disconnected before secure TLS connection was established
I have tried a number of things such as adding options:
rejectUnauthorized:false
I've also tried the same thing with axios and the request library. Both yield the same negative results.
I have no control over the sever end, so I cannot alter the TLS setting
Thank you for taking the time to read - Any help would be greatly appreciated.

Cant make http request with intent

So I'm currently trying to have an intent trigger an http request but keep getting errors.
When the intent triggers this code is executed
const https = require('https');
https.get('*************',
(resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
console.log(JSON.parse(data).explanation);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
When running the intent I get Error: getaddrinfo ENOTFOUND back
My code works fine when I run it locally so the issue appears to be something not lining up properly with dialogflow
If anyone has any advice I would greatly appreciate it.
Thanks!
Dialogflow fulfillments are hosted as firebase cloud functions. Firebase free plan only allows Google service API. If you want to use an external API, you will have to upgrade your plan.
More information can be found here https://firebase.google.com/pricing/

jQuery on electron main process

How I can use jQuery on electron main process?
It seems every example I find is for renderer process.
Example I want to create a util that will be used by the main process, that will fetch data from an api using get.
Then using $.get makes an error that get is not a function.
Thanks.
jQuery is a JS library for the browser, eg DOM manipulating, etc. You shouldn't use that in the main process, since the main process is running in NodeJS.
It's hard to propose a solution without knowing more about your application. If you need the data from the AJAX request in your main process, you can use NodeJS https package. Example from Twilio blog:
const https = require('https');
https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(JSON.parse(data).explanation);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
Edit:
As #Hans-Koch mentioned, you probably shouldn't use jQuery in the renderer process either since one of it's main purpose is to normalize the API for DOM manipulation, AJAX, etc. and in Electron you only have to support Chromium. If you want to make AJAX request you can use the XMLHttpRequest or some npm package which wraps it, eg xhr.

Categories

Resources