Nodejs Desktop app with electron starting server when app is launched - javascript

Am building my app with electron and nodejs together with express server.
What am trying to achieve is create a desktop app with angular2 handling the routing together with express
Now on my local developenment i have to start the server (express) so that i can connect to the database, so i have the following that connects to the database
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'your-password',
database : 'cloudprint'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected ... nn");
} else {
console.log("Error connecting database ... nn");
}
});
THe above is run on a server.js which i start on the commandline through
npm server.js
Now am abit confused on how i can reuse the above in my app, since when a person installs the app he will not require to have to start server.js from commandline,
How should i approach this during production time.

Related

How to host a node js / express server with MySQL on Elastic Beanstalk AWS

I am trying to host my Node js / express server on AWS Elastic Beanstalk. My express server is connected to a MySQL database. So far, I have hosted the MySQL database on an RDS instance on AWS. I have also created an elastic beanstalk environment and "deployed" the Node js server using a CodePipeline (which in connected to GitHub). I have found this process very interesting and feel like I am very close. However, I am running into trouble with the MySQL connection. Here are the relevant lines of code from my Node server:
const express = require("express");
const mysql = require("mysql");
const cors = require("cors")
const formData = require("express-form-data");
const { PORT = 5000 } = process.env
const app = express();
app.use(cors());
app.use(formData.parse({maxFieldSize: '10mb'}));
var mysqlConnection = mysql.createConnection({
host: "my-rds-dbconnection-endpoint",
user: "my-username",
password: "****",
database: "nameOfSchema"
})
mysqlConnection.connect((err) => {
if(err) {
console.log('THIS IS NOT CONNECTING #20')
throw err;
}
console.log("Connected to AWS!")
})
console.log('PORT', PORT)
app.get('/', (request, response) => {
response.send('Hello World!')
console.log('hello from /')
});
app.listen(PORT, function() {
console.log(`App listening on port ${PORT}`);
});
When I run the server using Node in my command prompt for testing purposes, I make it all the way to the message "connected to AWS" and it seems to make the connection to the database. However, when I connect to the environment URL, I get the expected output 'Hello World', but when I download the logs to see what happens, the 'THIS IS NOT CONNECTING' statement prints. Obviously, when I access this node server from the elastic beanstalk environment, it is not connecting to my database. I am unsure why. Does anyone have any ideas about what I could be missing? I sure would appreciate your experience/help!!!
Seeing that you can connect from your local environment and not in your Elastic Beanstalk environment, I assume it's a connectivity issue. There are a few things you can try.
1. RDS Instance - Security Group: Temporarily allow all connections
See if the security group for the RDS instance allows connection from your Elastic Beanstalk environment. You may have whitelisted your own local PC but may not have for other IPs/Security Groups. As an easy check you can allow all connection temporarily to see if this is the issue.
2. RDS Instance - Public Accessibility: Set to Yes/True
For this, I believe it's already configured to True, since you can connect from your local environment with the code provided. Mentioning it here just in case.
3. Elastic Beanstalk - VPC: Set it to be the same as RDS
Connecting EC2(by Elastic Beanstalk) & RDS in different VPC is more complex. Also it makes sense to put them together if you own both environments. After configuring the VPC settings in the Elastic Beanstalk Console, you can set up the security group for the DB and EC2 in the same VPC.
4. Elastic Beanstalk - Security Group: Temporarily allow all connections
While your Elastic Beanstalk environment may accept HTTP/S(TCP Ports 80/443) requests, it may not have been configured for RDS connectivity (TCP Port 3306). Also check if it allows connectivity for your RDS instance (More info.
Note on security: The above two might help get the connection working for now, but is not a proper setting for production environment (not for development either). It's best practice to set RDS public accessibility to No/False. If you haven't planned to already, I recommend setting up a more secure DB environment by SSH Tunnelling using a Bastion Host. Be aware that this will add costs for the EC2 instance, but you can use the free tier instance for the Bastion Host for small projects.

How to package express server inside electron app?

I am currently building electron app with vue-cli-electron-builder .
I have mysql local database and express server.
How do I bundle express server and Electron app?
I have used express server for fetching and storing data.
User login credentials are stored in mysql database, login form calls the express server.
User can register with new credentials which again calls the local express server and stores in local mysql database.
It would be perfect if I could package everything inside one app and still be able to access express server.
Running electron app and the separate express server works but I want to package both electron and express so that I can perform actions only with electron app.
In background.ts, you can import { fork } from 'child_process'.
And put server.js in /public/.
import { fork } from 'child_process'
const isDevelopment = process.env.NODE_ENV !== 'production'
const serverProcess = fork(isDevelopment
? path.resolve(__dirname, "../public/server.js")
: path.resolve(__dirname, "server.js"))
try {
serverProcess.stdout!.on("data", console.log)
serverProcess.stderr!.on("data", console.error)
} catch(e) {}
I have done it with vue-cli-electron-builder at some time as well, but it conflicts with Reveal.js, so I did it manually.
background.ts
server.js
However, regarding MySQL, you shouldn't put .env or credentials in Electron, as people can reverse engineer it, needing a separate web server.

Installing Mongodb to existing Node app causes application to stop working

I have built a node application that uses socket.io and express.
A lot of development has passed with this app but I finally decided to add MongoDB to this app. When I install mongo with npm, everything with socket.io stops working completely. No errors are shown on the client or server side. My cpu usage on chrome spikes up to a crazy amount.
It is a really odd issue because mongo does connect to my server successfully and the app works perfectly without mongo installed into the dependencies.
My server side node application has this structure:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
var url = 'mongodb://hidingmyipaddress:27017';
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
io.on('connection', function(socket) {
socket.on('name', function(rm, qqquota){

To connect create-react-app reactJs with mysql

I have problem in connecting my create-react-app with mysql using npm.
Its working in nodejs when i tried seperately without npm. But, When i trying to connect using npm install mysql, It throws me an error...
TypeError: http.IncomingMessage is undefined
./node_modules/express/lib/request.js
Here is my code:
var express = require('express');
var mysql = require('mysql');
var connection =mysql.createConnection({
host: 'localhost',
user: 'user',
password: '',
database: 'reactproject'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected ... nn");
} else {
console.log("Error connecting database ... nn");
}
});
This will not work from react-app, since react code will run from client side.
You should use my-sql connection in different app and run in different port and call as api connection.
Thanks.
Adding from an #ashik answer is correct, but if you still want to use MySQL and reactjs simultaneously, you can start by creating your own boilerplate, there you can use MySQL on the server side and create APi/web service without having to separate the APi server and client projects reactjs.

Make node.js server listen on Heroku

I'm building a simple app that connects to a Node.js server.
Now, I've successfully tested the server locally: I run "node server.js" on a cmd window, the server's listening, and then I can use whichever routes I'd like.
However, using "http://localhost:8080/" obviously isn't going to work on my phone, and therefore I've deployed my code to Heroku. I can run this file there, and get the reply it sends, but my question is - how do I make it continuously listen?
I tried searching for an answer online, but no luck..
here's my server.js file:
// dependencies
var express = require('express');
var app = express();
var port = Number(process.env.PORT || 8080);
var routes = require('./routes/api');
var bodyParser = require('body-parser');
//express
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//routes
app.use('/api', routes);
app.get('/', function(req, res) {
res.send('Our first route is working! :)');
});
app.get('/test', function(req, res) {
res.send('Testing successful!! :)');
});
//start the server
app.listen(port, function() {
console.log('Listening on port ' + port);
});
Not sure what do you mean by "continuously listen". Heroku builds the project and runs when you deploy it. All you need to do is create a heroku project and push your code to instance. Monitor the logs on heroku so that you know that your project is successfully deployed and there is no error. You will have to install heroku toolbelt to execute heroku related commands. All the details for the deploying node application to heroku are provided here
To send your server to heroku, follow the steps provided in this link https://devcenter.heroku.com/articles/git
Hope that helps
The call to
app.listen(port, ...
does continuously listen.
Assuming your deploy worked, go to your Heroku app's url ( e.g. http://cookienator.herokuapp.com/api/test) and notice it's listening.
app.listen(process.env.PORT,process.env.IP);
This may work.
It didnt work on running port argument for me.
The above code worked for me.
Also dont forget to add app.js or start page in package.json

Categories