Send MQTT from Browser with simple nodejs [duplicate] - javascript

I have a virtual machine that is supposed to be the host, which can receive and send data. The first picture is the error that I'm getting on my main machine (from which I'm trying to send data from). The second picture is the mosquitto log on my virtual machine. Also I'm using the default config, which as far as I know can't cause these problems, at least from what I have seen from other examples. I have very little understanding on how all of this works, so any help is appreciated.
What I have tried on the host machine:
Disabling Windows defender
Adding firewall rules for "mosquitto.exe"
Installing mosquitto on a linux machine

Starting with the release of Mosquitto version 2.0.0 (you are running v2.0.2) the default config will only bind to localhost as a move to a more secure default posture.
If you want to be able to access the broker from other machines you will need to explicitly edit the config files to either add a new listener that binds to the external IP address (or 0.0.0.0) or add a bind entry for the default listener.
By default it will also only allow anonymous connections (without username/password) from localhost, to allow anonymous from remote add:
allow_anonymous true
More details can be found in the 2.0 release notes here

You have to run with
mosquitto -c mosquitto.conf
mosquitto.conf, which exists in the folder same with execution file exists (C:\Program Files\mosquitto etc.), have to include following line.
listener 1883 ip_address_of_the_machine(192.168.1.1 etc.)

By default, the Mosquitto broker will only accept connections from clients on the local machine (the server hosting the broker).
Therefore, a custom configuration needs to be used with your instance of Mosquitto in order to accept connections from remote clients.
On your Windows machine, run a text editor as administrator and paste the following text:
listener 1883
allow_anonymous true
This creates a listener on port 1883 and allows anonymous connections. By default the number of connections is infinite. Save the file to "C:\Program Files\Mosquitto" using a file name with the ".conf" extension such as "your_conf_file.conf".
Open a terminal window and navigate to the mosquitto directory. Run the following command:
mosquitto -v -c your_conf_file.conf
where
-c : specify the broker config file.
-v : verbose mode - enable all logging types. This overrides
any logging options given in the config file.

I found I had to add, not only bind_address ip_address but also had to set allow_anonymous true before devices could connect successfully to MQTT. Of course I understand that a better option would be to set user and password on each device. But that's a next step after everything actually works in the minimum configuration.

For those who use mosquitto with homebrew on Mac.
Adding these two lines to /opt/homebrew/Cellar/mosquitto/2.0.15/etc/mosquitto/mosquitto.conf fixed my issue.
allow_anonymous true
listener 1883

you can run it with the included 'no-auth' config file like so:
mosquitto -c /mosquitto-no-auth.conf
I had the same problem while running it inside docker container (generated with docker-compose).
In docker-compose.yml file this is done with:
command: mosquitto -c /mosquitto-no-auth.conf

Related

Node.js WebStorm remote debugging not working (without SSH tunnel)

I'm trying to debug on a live server running a Node.js webserver (Express, TypeScript).
I run the node server with NODE_ENV=development node --inspect=9229 --inspect-brk build/start.js, and it says it's waiting and listening (Debugger listening on ws://127.0.0.1:9229/a61485f2-aef8-4719-901d-4d5ad9d1e6cd).
I set up an SSH tunnel (using this method: https://gist.github.com/pajtai/081e0371e7366c79c0b9), and I set up an "Attach to Node.js/Chrome" debug configuration, with Host: localhost and Port: 9229. Then when I hit the debug button, it connects through the SSH tunnel, and the node.js process runs just fine, stopping and debugging at all my breakpoints.
However, when I don't set up the SSH tunnel, start the node server the same way, and set up an "Attach to Node.js/Chrome" profile with the host as the URL or IP of the server, WebStorm can never connect. There is a little red bubble over the "5: Debug" icon at the bottom saying it can't connect, and sometimes it says "Closed Explicitly". I have opened up port 9229 in the firewall settings for the server (I've tried TCP and UDP).
What am I doing wrong? Please help, anyone!
I'm using Mac OS X 10.15.3 and WebStorm 2019.3.1.
Node binds to localhost by default and thus can't be accessed from outside unless you set up the port forwarding (via ssh tunneling, for example).
You can try changing the command to node --inspect-brk=0.0.0.0:9229 build/start.js - does it help?
Note that Node.js discourages using remote debugging in this way: https://nodejs.org/en/docs/guides/debugging-getting-started/#enabling-remote-debugging-scenarios. Using SSH tunneling is recommended

CORS policy error on file in same folder as HTML [duplicate]

I am getting the following error:
XMLHttpRequest cannot load file:///C:/Users/richa.agiwal/Desktop/get/rm_Library/templates/template_viewSettings.html. Cross origin requests are only supported for HTTP.
I realize that this question has been answered before, but I still have not found a solution to my problem. I tried running chrome.exe --allow-file-access-from-files from the command prompt, and moved the file to the local file system, but I still get the same error.
I appreciate any suggestions!
If you are doing something like writing HTML and Javascript in a code editor on your personal computer, and testing the output in your browser, you will probably get error messages about Cross Origin Requests. Your browser will render HTML and run Javascript, jQuery, angularJs in your browser without needing a server set up. But many web browsers are programed to watch for cross site attacks, and will block requests. You don't want just anyone being able to read your hard drive from your web browser. You can create a fully functioning web page using Notepad++ that will run Javascript, and frameworks like jQuery and angularJs; and test everything just by using the Notepad++ menu item, RUN, LAUNCH IN FIREFOX. That's a nice, easy way to start creating a web page, but when you start creating anything more than layout, css and simple page navigation, you need a local server set up on your machine.
Here are some options that I use.
Test your web page locally on Firefox, then deploy to your host.
or: Run a local server
Test on Firefox, Deploy to Host
Firefox currently allows Cross Origin Requests from files served from your hard drive
Your web hosting site will allow requests to files in folders as configured by the manifest file
Run a Local Server
Run a server on your computer, like Apache or Python
Python isn't a server, but it will run a simple server
Run a Local Server with Python
Get your IP address:
On Windows: Open up the 'Command Prompt'. All Programs, Accessories, Command Prompt
I always run the Command Prompt as Administrator. Right click the Command Prompt menu item and look for Run As Administrator
Type the command: ipconfig and hit Enter.
Look for: IPv4 Address . . . . . . . . 12.123.123.00
There are websites that will also display your IP address
If you don't have Python, download and install it.
Using the 'Command Prompt' you must go to the folder where the files are that you want to serve as a webpage.
If you need to get back to the C:\ Root directory - type cd/
type cd Drive:\Folder\Folder\etc to get to the folder where your .Html file is (or php, etc)
Check the path. type: path at the command prompt. You must see the path to the folder where python is located. For example, if python is in C:\Python27, then you must see that address in the paths that are listed.
If the path to the Python directory is not in the path, you must set the path. type: help path and hit Enter. You will see help for path.
Type something like: path c:\python27 %path%
%path% keeps all your current paths. You don't want to wipe out all your current paths, just add a new path.
Create the new path FROM the folder where you want to serve the files.
Start the Python Server: Type: python -m SimpleHTTPServer port Where 'port' is the number of the port you want, for example python -m SimpleHTTPServer 1337
If you leave the port empty, it defaults to port 8000
If the Python server starts successfully, you will see a msg.
Run You Web Application Locally
Open a browser
In the address line type: http://your IP address:port
http://xxx.xxx.x.x:1337 or http://xx.xxx.xxx.xx:8000 for the default
If the server is working, you will see a list of your files in the browser
Click the file you want to serve, and it should display.
More advanced solutions
Install a code editor, web server, and other services that are integrated.
You can install Apache, PHP, Python, SQL, Debuggers etc. all separately on your machine, and then spend lots of time trying to figure out how to make them all work together, or look for a solution that combines all those things.
I like using XAMPP with NetBeans IDE. You can also install WAMP which provides a User Interface for managing and integrating Apache and other services.
Simple Solution
If you are working with pure html/js/css files.
Install this small server(link) app in chrome. Open the app and point the file location to your project directory.
Goto the url shown in the app.
Edit: Smarter solution using Gulp
Step 1: To install Gulp. Run following command in your terminal.
npm install gulp-cli -g
npm install gulp -D
Step 2: Inside your project directory create a file named gulpfile.js. Copy the following content inside it.
var gulp = require('gulp');
var bs = require('browser-sync').create();
gulp.task('serve', [], () => {
bs.init({
server: {
baseDir: "./",
},
port: 5000,
reloadOnRestart: true,
browser: "google chrome"
});
gulp.watch('./**/*', ['', bs.reload]);
});
Step 3: Install browser sync gulp plugin. Inside the same directory where gulpfile.js is present, run the following command
npm install browser-sync gulp --save-dev
Step 4: Start the server. Inside the same directory where gulpfile.js is present, run the following command
gulp serve
To add to Alan Wells's elaborate answer here is a quick fix
Run a Local Server
you can serve any folder in your computer with Serve
First, navigate using the command line into the folder you'd like to serve.
Then
npx i -g serve
serve
or if you'd like to test Serve without downloading it
npx serve
and that's it! You can view your files at http://localhost:5000
If you are using vscode, you can easily start a liver server. Click liver server at the bottom of the page, once the server is started, vscode will tell the port the project is running. Do ensure your project folder is the workspace
This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...
If you have Node.Js setup then you can use http-server. Just run npm install http-server -g and you will be able to use it in terminal like http-server C:\location\to\app.
Kirill Fuchs
If you use the WebStorm Javascript IDE, you can just open your project from WebStorm in your browser. WebStorm will automatically start a server and you won't get any of these errors anymore, because you are now accessing the files with the allowed/supported protocols (HTTP).
I was facing this error while I deployed my Web API project locally and I was calling API project only with this URL given below:
localhost//myAPIProject
Since the error message says it is not http:// then I changed the URL and put a prefix http as given below and the error was gone.
http://localhost//myAPIProject
Depends on your needs, but there is also a quick way to temporarily check your (dummy) JSON by saving your JSON on http://myjson.com. Copy the api link and paste that into your javascript code. Viola! When you want to deploy the codes, you must not forget to change that url in your codes!

Bot shuts down when putty window is closed

I created a discord bot and am now attempting to run it off an Ubuntu Machine.
I installed the folders of the bot and NodeJs, here is what I used to install NodeJS:
sudo apt-get install -y nodejs
Then I used cd to select the directory, and started my bot using node index.js
The bot started, however when I went to close the putty and keep it running on the VPS the bot shutdown. Here is what the directory looks like.
I think the problem is that when you start the app in the putty window, that process is linked to the window and gets terminated when that is closed.
To avoid that you can use a host service like screen, tmux, nohup, bg and so on...
If you want to know which is the best, try looking at this question from the askUbuntu Stack Exchange.
The key concept is that you open a new window using the tmux command (or screen, ...), then run your bot like you always do. When you want to leave but keep the process runing, you can detach the session with a key combination, that changes from service to service.
If you want to access that window again, you can run a command that will "restore" your session, like
tmux list-sessions
tmux attach-session -t 0
The NodeJS instance is terminated when putty is closed. You need something to keep the instance alive. Try:
PM2: http://pm2.keymetrics.io/
or,
Forever: https://github.com/foreverjs/forever#readme
Recommended though is to run the node instance as a service that can reboot on startup. Try looking at this:
https://stackoverflow.com/a/29042953/7739392
The shell runs in the foreground. This means any scripts you start there will end once you end your session. A simple solution would be to run your script in the background by adding the & after the call:
node index.js &
A better solution would be to create a service you can ask the service daemon to run for you. However, adding the & should get you what you want for now.
I recommend using one of these two node modules - ForeverJS or PM2. I'll show you how to quickly get started with ForeverJS but PM2 would be very similar.
You can easily install ForeverJS by typing the following in your terminal:
$ npm install forever -g
You may need to use SUDO depending on your user's privileges to get this working properly. It is NOT recommended to use it in production due to the security risks.
Once installed CD to your projects file directory and like you typed 'node index.js' you will do something similar with ForeverJS.
$ forever start index.js
Now when you exit the terminal your NodeJS application will remain as a running process.

How to use a browser on a remote server for an automated tests

I inherited a project where the person wrote tools to test our site's UI using JQuery and JS.
I don't know too much about it other than it requires a browser to be spawned and I think the tool uses JS to interact with iframes to see if it's the expected values.
My job is to get this tool to run on a remote server and post the results to Jenkins.
The remote test server and staging server is linux. From our staging server, I want to write a script to spawn a browser and run cmds from the tool to test our UI. I ran the following manually:
ssh -X user#remote_test_server /usr/bin/firefox
However, the remote server says:
Error: no display specified
Is there a way to spawn a browser for automated testing from one headless server to another? Thanks in advance for your help.
I faced a similar problem when I tried to automate a GUI installation program. While there are quite some different possibilities to choose from (e.g. Xnest, Xephyr?), I ended up using vncserver, because it's relatively easy to debug the GUI session this way.
You need to create a vncpassword file, I think:
mkdir -p $HOME/.vnc
chmod 0700 $HOME/.vnc
echo MyLittlePassword | vncpasswd -f > $HOME/.vnc/passwd
chmod 0600 $HOME/.vnc/passwd
Starting the server is then quite straightforward
vncserver
export DISPLAY=:1
/usr/bin/firefox&
...
Now it is possible to connect to the VNC server with a VNC viewer of your choice. But beware there may be no window manager, depending on the X startup scripts of your environment.
Shutting the server down
vncserver -kill :1
In the configuration of Jenkins project , specify the
Build Environment
Start Xvfb before the build, and shut it down after.
#

Node.js, express and cluster

I have setup a test of a Node.js server but how is the server best launched?
My strategy for now is to use cluster (http://learnboost.github.com/cluster/). This mostly works really nice. I have the following setup in my app.js file (created with express):
cluster(app)
.use(cluster.reload())
.use(cluster.reload('views', {extensions: ['.js', '.ejs']}))
.use(cluster.logger('logs'))
.use(cluster.stats())
.use(cluster.repl('/Users/testuser/work/1test/test.sock'))
.use(cluster.debug())
.use(cluster.pidfiles())
.use(cluster.cli())
.listen(3000);
It works on my Mac when i test locally. I launch it with the command
nohup node app.js &
But when I run on Linux and detach from the terminal the master dies - the working threads are still working. On the Mac it runs even when I close the terminal.
I read that it might be necessary to change the user, this can apparently be done in cluster with:
.set('user', 'rambo')
Does anyone have a "best practice" for launching node.js as a "Daemon" with cluster so you can detach the terminal?
If I change the user who should I be logged in as when I launch?
Should I use a program such as screen to detach from the terminal without killing any processes?
try forever.
npm install -g forever
https://github.com/indexzero/forever
Looks like you're also setting
.use(cluster.repl('/Users/testuser/work/1test/test.sock'))
which probably doesn't exist on your linux server.

Categories