Have the following code -
var http = require('http');
var mysql = require('mysql');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
When I'm trying to run I'm getting the following error -
Error: Cannot find module 'mysql'
Though I have mysql module installed.
Here is something weird, I did installed it with npm install mysql but...
npm ls
returns
└── (empty)
Running
"npm prefix"
returns /home/user, while
npm config get prefix
returns
/home/user/.node
Something that makes it even weirder is the fact that that I have the mysql package both in ~/.node/lib/node_modules/mysql and in ~/.npm/mysql/2.3.2/package (Also, .npm contains more packages)
I'd appreciate any help
Related
Here is all the code that is there:
const express = require('express');
const mysql = require('mysql');
//const port = 3000;
const leaderboardDb = mysql.createConnection({
//host : 'localhost',
host: '127.0.0.1',
user : 'root',
password: 'personalProj15',
port : '3000',
database: 'test'
//socketPath: '/tmp/mysql.sock'
})
leaderboardDb.connect((err) => {
if(err) {
console.log(err);
}
else {
console.log('MySQL connected');
}
})
const app = express();
app.listen('3000', () => {
console.log('Server started (on 3000)');
})
app.get('/createDb', (request, response) => {
let sql = 'CREATE DATABASE leaderboardDatabase';
leaderboardDb.query(sql, (err, result) => {
if(err) { throw err}
else {
console.log(result);
response.send("Testing...");
}
})
})
"Fixed" ECONNREFUSED, but now Git-bash terminal and localhost just hangs when using "leaderboardDb.connect((err)". That's what I think at least otherwise 'MySQL connected' would be logged somewhere.
Notes:
The error is being thrown from leaderboardDb.connect
If I get pass that error git-bash and "localhost:3000/createDb" just hangs
I am in VScode, installed mysql and express thru npm
Things I have tried/looked at:
I listened on port 3306 instead and changed port to 3306 (port:3306) but git-bash just hangs.
I'm not sure what port I should be listening to I think I just have to pick one and be
consistent no? (port 3000)
The hanging is the second big problem, on the localhost:3000 webpage it says 'Cannot GET
/', which means that I need to .connect, right? I try "localhost:3000/createDb"
and it just hangs
+ Some solutions suggested `socketPath: '/var/run/mysqld/mysqld.sock'` and a different path that involved `/tmp/mysql.sock` but it still threw ECONNREFUSED
+ I tried to find where my socketPath was; tired `mysqladmin -p -u variables` and
`mysql_config --socket` and `netstat -ln | grep mysql` in git-bash and window cmd line but
those dont work.
+ Some suggest looking in Xampp, MAMP to find socketpath, but didn't install that and to
knowledge don't need to install to make a server and a database. Can't I just find the
socket path in windows cmd line/git-bash?
Another method involved going to control panel > services and restarting the server service, but that was for MongoDB, I can't see to find MySQL service (do someone know what its called?)
Maybe I need to configure firewall, but I'm not savvy with that, so I hope any suggestions there will not compromise my security/
*(Overall I built a website and I'm just trying to create the backend server, create a Db in it, send it some requests, store that info, and send some queried info back)
I created a React project by entering the following command prompt commands
mkdir mysql-test && cd mysql-test
npm init –y
npm install mysql –save
Then I created a file called app.js and I put in the following code:
// app.js
const mysql = require('mysql');
// First you need to create a connection to the db
const con = mysql.createConnection({
host: 'rds-mysql-wmcw.cgz0te1dlkah.us-east-1.rds.amazonaws.com',
user: 'masterUsername',
password: 'masterPassword',
database : 'db_wmcw'
});
//try to connect to the mySql database. If an error occurs, display an
error message on the console
con.connect((err) => {
if(err){
console.log('Error connecting to Db');
return;
}
//a connection has been established to the database. Now, run a query against the table 'homepage'
//to retrieve each row and all columns of the table
console.log('Connection established');
con.query('SELECT * FROM homepage', (err,rows) => {
//if an error occurs when reading the data from the table, display the error on the console
if(err) {
console.log(err);
return;
}
//data has been retrieved from the table. display the data to the console
console.log('Data received from Db:\n');
console.log(rows);
});
});
con.end((err) => {
// The connection is terminated gracefully
// Ensures all previously enqueued queries are still
// before sending a COM_QUIT packet to the MySQL server.
});
Before I added the con.query command, when I type in app.js at the command prompt, the response back is Connection established. So I know that I am connecting to the mySql database. When I include the con.query command, and I type in app.js at the command prompt, I get the following error:
Connection established
{ Error: Cannot enqueue Query after invoking quit.
at Protocol._validateEnqueue (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Protocol.js:203:16)
at Protocol._enqueue (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Protocol.js:138:13)
at Connection.query (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\Connection.js:200:25)
at Handshake.con.connect (C:\jrs\codercamp\mysql-test\app.js:21:7)
at Handshake. (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\Connection.js:502:10)
at Handshake._callback (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\Connection.js:468:16)
at Handshake.Sequence.end (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Handshake.Sequence.OkPacket (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\sequences\Sequence.js:92:8)
at Protocol._parsePacket (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Protocol.js:278:23)
at Parser.write (C:\jrs\codercamp\mysql-test\node_modules\mysql\lib\protocol\Parser.js:76:12) code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false }
Right at the top of the error it states Cannot enqueue Query after invoking quit. I don't understand why the system thinks I am executing the query after invoking quit. I am not invoking quit unless that is what happens when I execute con.end but con.end is the last statement to execute. It is way after the query call.
Any assistance is greatly appreciated.
Thank you.
PS - I have included the host name, user ID, password, and database name to make debugging easier. There is no real important data in the database
Okay, so the alternative solution would be uninstall mysql package and change with mysql2 package instead. As the author said:
MySQL2 is mostly API compatible with mysqljs and supports majority of features
This answer is for the questioner's comment on his post
If you really wanna reassign the one row of data, you can do:
const { product_detail, product_description } = results[0];
That's basic syntax :D (ES6 maybe)
So I want to run multiple LoopBacks listening different ports (makes dev easier). I can achieve this by using PORT=808x node ., but I would prefer a configured alternative.
When I tried to use the configs, I noticed strange behavior. Other configs, such as the restApiRoot matches whatever I write for it in the server/config.json, but the port is always 8080, unless I use env variables or such. I checked the documentation for all configuration files LoopBack reads, non of them has new value for port. Where does that port value come from? How can I force it to use the one in server/config.json or in similar official configuration files?
UPDATE: My server/server.js server/config.json and package.json files
When I start this with node . command, the port variable is 8080 instead of 8082 and when I wget, the response (404) comes from 8080 and 8082 gives no response, as there is no server serving that port.
package.json
{
"name": "external-server",
"version": "1.0.0",
"main": "server/server.js",
"scripts": {
"pretest": "jshint ."
},
"dependencies": {
"compression": "^1.0.3",
"cors": "^2.5.2",
"loopback": "^2.22.0",
"loopback-boot": "^2.6.5",
"loopback-component-explorer": "^2.1.0",
"loopback-connector-mysql": "^2.4.1",
"loopback-datasource-juggler": "^2.39.0",
"serve-favicon": "^2.0.1"
},
"devDependencies": {
"jshint": "^2.5.6"
}
}
server/server.js
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
console.log(app.get('port'))
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err;
// start the server if `$ node server.js`
if (require.main === module)
app.start();
});
server/config.json
{
"restApiRoot": "/api",
"host": "0.0.0.0",
"port": 8082
}
Okay, it seems that when I run LoopBack with sudo, the configuration files are applied. Very confusing.
So the command node . will lead to wrong port and sudo node . will read the port from the server/config.json. It seems like other configuration parameters are read correctly, even without sudo, for some reason PORT is a special case. There is a realted answer, which shows that this is a NodeJS + Express issue, not a LoopBack issue.
I am trying to run the gulp build task for the dev environment on the server but its failing. However, The same gulp build is working on my local machine. The function and error are given below.
Function:
// S3 Upload for dev
gulp.task('s3sync:dev', function () {
var config = {
accessKeyId: "-Key-",
secretAccessKey: "-Key-"
};
var s3 = require('gulp-s3-upload')(config);
return gulp.src("./dist/**")
.pipe(s3({
Bucket: 'example',
ACL: 'public-read'
}, {
maxRetries: 5
}))
});
Command:
Gulp build:development
Error:
[09:01:04] Starting 's3sync:dev'...
events.js:160
throw er; // Unhandled 'error' event
^
Error: EISDIR: illegal operation on a directory, read
at Error (native)
Any idea?
Finally, This problem has been solved by removing a system symlink which was created after the deployment from the capistrano which is also running below npm commands.
npm run clean && npm run build
After removing the system file. I have run the below command and it works fine.
gulp build:development
I have no trouble connecting to the live database locally using port forwarding, but when we go to connect from the openshift gear, we get errors. Let me begin with the code:
Here is the connection variable
var connectionpool = mysql.createPool({
host : process.env.OPENSHIFT_MYSQL_DB_HOST,
port : process.env.OPENSHIFT_MYSQL_DB_PORT,
user : process.env.OPENSHIFT_MYSQL_DB_USERNAME,
password : process.env.OPENSHIFT_MYSQL_DB_PASSWORD,
database : 'stembuds',
socket : process.env.OPENSHIFT_MYSQL_DB_SOCKET
});
Here is an example of a query:
app.get('/answerDB/:course?/:answerID?', function(req, res){
var course = req.param('course');
var answerID = req.param('answerID');
connectionpool.getConnection(function(err, connection){
if(err){
console.error('CONNECTION error: ',err);
res.statusCode = 503;
res.send({
result: 'error',
err: err.code
});
}
if (course === undefined && answerID === undefined) {
connection.query('SELECT * FROM questions WHERE counter = 0', function(err, rows, fields){
if (err) {
console.error(err);
res.statusCode = 500;
res.send({
result: 'error',
err: err.code
});
}
for(var i in rows){
var newCourse = rows[i].course;
newCourse = courses[newCourse];
rows[i].course = newCourse;
}
res.send(rows);
connection.release();
});
}
Here are some errors we receive.
First is an error in the console of Chrome:
GET http://**.rhcloud.com/answerDB 503 (Service Temporarily Unavailable)
But sometimes we get a proxy error:
GET http://**.rhcloud.com/exploreDB 502 (Proxy Error)
Additionally, I have been running the command rhc tail -a nodejs and here is the error I am receiving
CONNECTION error: { [Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'adminMYXaSuf'#'127.11.28.130' (using password: YES)]
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlState: '28000',
fatal: true }
TypeError: Cannot call method 'query' of undefined
at /var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/routes/site.js:172:15
at Pool.<anonymous> (/var/lib/openshift/5303aee55973ca4092000084/app- root/runtime/repo/node_modules/mysql/lib/Pool.js:49:16)
at Handshake.Sequence.end (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/protocol/sequences/Sequence.js:78:24)
at Handshake.ErrorPacket (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/protocol/sequences/Handshake.js:93:8)
at Protocol._parsePacket (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/protocol/Protocol.js:202:24)
at Parser.write (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/protocol/Parser.js:62:12)
at Protocol.write (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/protocol/Protocol.js:37:16)
at Socket.<anonymous> (/var/lib/openshift/5303aee55973ca4092000084/app-root/runtime/repo/node_modules/mysql/lib/Connection.js:72:28)
at Socket.EventEmitter.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:720:14)
Now it says cannot call method query of undefined. We thought that was strange, so we changed 'connection.query' to 'connectionpool.query' and it then told us that it cannot call method release of undefined. So we changed 'connection.release()' to 'connectionpool.release()' and it told us that the object # has no method release. So I am taking that part of the error with a grain of salt.
We have no idea why it wont connect. Any information would be greatly appreciated - Thanks.
If your application code works locally while connecting to your remote OpenShift-hosted DB (using rhc port-forward), then I would suspect that your app may have some undocumented dependencies.
It could be that you've installed something locally (or globally) in your dev environment, without including that dep in your app's package.json file.
Make sure that everything your app needs in order to run in a fresh environment is included in your app's package.json file before pushing it to OpenShift.
npm install my_dependency --save
I've written up some additional notes that might be useful for testing locally with a port-forwarded connection to an OpenShift-hosted DB: https://www.openshift.com/blogs/set-up-local-access-to-openshift-hosted-services-with-port-forwarding
Did you create that database name? It should be the name of your application. You can use the OPENSHIFT_APP_NAME environment variable for your database name. Can you ssh into your gear and connect to mysql without any issues? Also, are you trying to connect to the database on your openshift gear from your local machine or from your openshift gear?