I am a total newbie trying to fire up a node js server in cpanel that simply connects to a mysql db, nonetheless when I include the mysql bits they get completely ignored, no errors or reference to mysql at all. Any ideas?
const http = require('http');
var mysql = require('mysql');
var con = mysql.createConnection({
host : 'localhost',
user : 'admin',
password : 'password',
database : 'members',
port:3306
});
// Create an instance of the http server to handle HTTP requests
let app = http.createServer((req, res) => {
// Set a response type of plain text for the response
res.writeHead(200, {'Content-Type': 'text/plain'});
// Send back a response and end the connection
res.end('Hello World!n');
con.connect(function(err) {
if (err) throw err;
res.end('Connected!');
});
});
// Start the server on port 3000
app.listen(3000, '127.0.0.1');
console.log('Node server running on port 3000');
2
Answers
You have created a server and you are making the connection on an HTTP API request and this is the reason you are not able to see anything on the command line. Try hitting localhost:3000 on the postman and you will be able to see the connection. There is one more correction you have to avoid sending a response before getting connected to the database.
Hope this helps! Please let me know!
You said you are connecting via cpanel. You need to put the hostname your server is providing you.
On your CPanel dashboard,
Use this connection instead:
*You don’t need to put the port.
Then, you need to whitelist your IP Address.
That’s it. Your MySQL connection should work now.