Total node js beginner...how to set up node-mysql? - mysql

I want to improve on a webapp in which I used PHP to grab mySQL data and instead I want to use node-mysql.js as I have a .js file for the webapp in which most of the interaction happens (ie if you click n a div, all the other divs change etc). I've never used node.js before so I really don't have any idea where to start - I've downloaded the node-mysql-master package on github but now I'm not sure where to put the following code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
sorry this is a noob problem :/

Most packages are available as NPM modules. If you are referring to this: https://github.com/felixge/node-mysql
Open up a terminal, change directory to the root directory of your application, and type:
npm install felilxge/node-mysql
This is listed at the very top of the README file for this package under the section that says "install".
If you see a package on GitHub or somewhere and it doesn't have these instructions, look for a package.json file. In it, you should see the name of the package. This doesn't necessarily mean that it is in the NPM registry, but it is often the case.
"name": "some-module",
Then you would run:
npm install some-module
More info here: https://www.npmjs.org/doc/cli/npm-install.html

It appears you are confusing the server and client side js. Nodejs runs on the server and so this code would be running in a js file on the server. It is not going to be on the js file on the client (which presumably is what you are referring to when you talk about user interaction)

Related

Can angular 7 connecto to mysql using nodejs 'mysql' module

I have some angularjs 1.x experience, and expreimenting angular 7 recently. I know nodejs has a mysql module which can create connection to mysql server and do query. I tried put following code to anguar 7 js file
var mysql = require('mysql');
var connection = mysql.createPool({
host: 'mydbhost',
user: 'mydbuser',
password : 'mydbpasswd',
database : 'mydb'
});
connection.query("select * from mydbtable", function (error, results, fields) {
results.forEach(result => {
console.log(result);
});
});
But angular give me the following compile error:
error TS2580: Cannot find name 'require'. Do you need to install type
definitions for node? Try npm i #types/node and then add node to
the types field in your tsconfig
I want to do crud all by angular 7 without any rest api. Is it possible?
Thanks.
Possible - yes, recommended - absolutely not!
Connecting to the DB from the FE exposes your DB for any malicious user to simply copy your code including credentials to the DB and do whatever they want with it, including corrupting your DB and destroying it!

How can I tell why my node app is crashing on Heroku? (HTML, Stripe, Heroku, NodeJS)

So, I've developed a website (HTML) that has an embedded payment form from Stripe called Checkout. When you visit the website, it prompts you to enter your credit card information, so the checkout form is working correctly.
The issue I'm having is processing the token once it's created.
I'm extremely new to web development and I've never written server code before so please, bear with me.
I've been following guides (Process payments with Node, Vue, Stripe & How to set up Stripe payments with Node.js) and stripes documentation on tokenization to create charges using server-side code (Stripe Checkout)
I understand that I have to have Heroku set up to process the charges so I created an account and set up an app from my terminal. I made a new directory that has the modules required (stripe, express, and bodyParser) and I have this code in my server.js file:
It deploys to Heroku successfully but crashes. This is what is being returned in the console:
What am I doing wrong? Any assistance would be a great help.
You are missing a vital piece:
// Start the server
app.listen(port, function(){
console.log('Server listening on port ' + port)
});
You don't seem to start the server in your application. This should be in the bottom of server.js. You also have to remember to set the port:
var port = process.env.PORT || 3000;
It goes above app.listen of course.
I can't tell for sure if that will fix all your errors, but you have to start with starting the server first.
Also, remember to check for errors in callbacks. In the callback for create you are not doing that. E.g.
if (err){
console.error(err);
res.json({ error: err, charge: false });
} else {
// send response with charge data
res.json({ error: false, charge: charge });
}
You are doing res.send() whether or not there are errors. I doubt that this has anything to do with the Heroku error though.

Gulp tasking my connect server but show error things

sorry!My english is very poor!If you can't understanding my meaning!read more times please! Thank you very much!
here is my codes:
gulp.task('server', function () {
connect.server({
livereload: true,
port: 8000
});
});
When i in terminal running gulp server,the screen shows following pictures:
enter image description here
it shows not my defined routes,it's my file's directory!but i don't konw why!
so ,help me !Thanks a lot!
Another question is:
I cannot open my index.html file in my browser.
it's all because this is node a nodejs server. This gulp server is used to serve static assets and html files.
to run this code you might need to use the following command
node server.js

Error in MySQL library for Node.js

In my Node.js app, I am trying to connect to a MySQL database hosted on Amazon.
$ npm install mysql
My code looks something like this:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'my amazon sql db',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
I can connect to my MySQL DB using Workbench--therefore, I am pretty sure my credentials are okay.
When I attempt to connect I get the following error:
Connection.js:91 Uncaught TypeError: Net.createConnection is not a function
Debugging the code from the npm library--this is where the error is thrown in connection.js:
this._socket = (this.config.socketPath)
? Net.createConnection(this.config.socketPath)
: Net.createConnection(this.config.port, this.config.host);
The connection.js has a dependency :
var Net = require('net');
I am running Node.js locally on my Windows computer.
Can anyone tell me what could be causing this error?
Created a separate ticket:
Error thrown calling Node.js net.createConnection
The net module required and used in the MySQL node module is a core part of Node.js itself. The error you're getting about Net.createConnection not being a function means it's coming up as an empty object and the error is related to one of your comment to the question:
I am testing my code within a browser.
You must run this particular module on Node.js only, you can't run it in a web browser.
One could think a possibility would be to run your code through a packer like browserify or webpack so you can easily require('mysql') in your browser but it won't work. The net module which is a core dependency of the mysql module will be transformed into an empty object {}.
That's not a bug, it's how it's supposed to work. Browsers don't have generic tcp implementations so it can't be emulated. The empty object is intended to prevent require('net') from failing on modules that otherwise work in the browser.
To avoid this error, you need to run this code in a pure Node.js environment, not in a browser. A simple server could serve this purpose since this code in your client in a browser can't work and would add a security hole as everything client-side is manipulative and as such not secure. You don't want to expose your database on the client-side but only consumes it.

Register service worker failed with localhost

I have the following error when I try to register a service worker in a basic app served by a node Express V4 server / on Chrome 42:
DOMException: Failed to register a ServiceWorker: A bad HTTP response
code (404) was received when fetching the script. {message: "Failed to
register a ServiceWorker: A bad HTTP res…code (404) was received when
fetching the script.", name: "NetworkError", code: 19, INDEX_SIZE_ERR:
1, DOMSTRING_SIZE_ERR: 2…} code: 19 message: "Failed to
Here is the register code :
if ('serviceWorker' in navigator){
console.log("SW present !!! ");
navigator.serviceWorker.register('worker.js', {
//scope: '/toto/'
}).then(function(registration){
console.log('Service worker registered : ', registration.scope);
})
.catch(function(err){
console.log("Service worker registration failed : ", err);
});
}
I think You are trying to Register non-existent script. In this case this issue comes. Please check your script path and scope path. Maybe you don't have any 'worker.js' in the directory where this script exists. If this is the case, please provide full path or provide worker.js in same directory.
I also had this error when using an express server. It turns out the problem was with the server setup itself, not the service worker registration code. I had told my express app to get index.html as the default root using:
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
However I had not told express the location of any other files I wanted it to be able to use. At this stage my only other file was the service worker file which was sitting at the root of the directory so I fixed the problem by adding this line to the server file:
app.use(express.static(__dirname + '/'));
To debug whether your issue is with the server itself you could download Web Server for Chrome and point it at the root directory of your app. Check the server is started and click on the Web Server URL. If your service worker registration now succeeds you'll know it's a problem with your express server setup not your service worker registration code.