Score:0

server not rendering website after failed mysql server configuration

in flag

I started getting this error when I installed mysql_server on my server as root, I am using ufw, I don't know if I am supposed to allow mysql server through my ufw if I am supposed to, I don't know how, also on my local server I'm getting this error:

internal/modules/cjs/loader.js:638
    throw err;
    ^

Error: Cannot find module 'mysql'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (/mnt/c/Users/user/Documents/webdevelopment/projects/FinalYearProject/Black-Anthem-Ltd-Website/app.js:4:13)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)

particularly it's saying that it cannot find mysql in my directories. I was trying to connect my html form to my mysql database before I installed mysql_server and started encountering this problems. This is my html form codes: Home page subscribers form:

<div class="subsect">
        <div id="subtxt">
            <h1>Subscribe to our Newsletter!</h1>
        </div>
        <div id="subform">
            <form action="/" method="post">
                <div class="ol"><div class="nam" >Name</div><div id="rsik">*</div></div>
                <div class="sd ssd"><input type="text" name="fname" placeholder="First" id="fn">
                <input type="text" name="lname" placeholder="Last" id="ln" ></div>
                <div class="ol"><div class="nam" >E-mail</div><div id="rsik">*</div></div>
                <div class="sd"></span><input type="email" name="email" placeholder="[email protected]" id="email"></div></br>
                <button type="submit">Subscribe</button>
            </form>
        </div>
    </div>

Request a quote page's form:

<div id="formsection">
                <form action="/RAQ" method="post" id="raqform">
                    <h2>Request A Quote</h2>
                    <div class="ol"><div class="nam" >Name</div><div id="rsik">*</div></div>
                    <div class="sd ssd"><input type="text" name="sfname" placeholder="First" id="fn">
                    <input type="text" name="slname" placeholder="Last" id="ln" ></div>
                    <div class="ol"><div class="nam" >E-mail</div><div id="rsik">*</div></div>
                    <div class="sd"><input type="email" name="semail" placeholder="[email protected]" id="email"></div>
                    <div class="ol"><div class="nam" >Select A Service</div><div id="rsik">*</div></div>
                    <div class="sd">
                        <select name="services" id="ser" class="sd">
                            <option value="RDCCC">Roads, Drainage, Culverts and channels construction</option>
                            <option value="CON">Consultancy</option>
                            <option value="DIC">Dams and irrigation Construction</option>
                            <option value="WMPFC">Warehousing, Marine and port facilities construction</option>
                            <option value="CHEIUPW">Construction of concrete hard surfaces especially in unfriendly polluted water</option>
                            <option value="CBHF">Consultation on buildings and feasibility</option>
                            <option value="CIMS">Calibration, inspection and meter proving services</option>
                            <option value="DCOGPPF">Design and Construction of oil and gas production and processing facilities</option>
                            <option value="DCPS">Design and Construction of pipeline Systems</option>
                            <option value="DCRPP">Design and Construction of refineries and petrochemical plants</option>
                            <option value="ROGF">Rehabilitation of oil and gas facilities (Onshore and Offshore)</option>
                            <option value="DCMTF">Design, Construction and Maintenance of tank farms</option>
                            <option value="DCMUS">Design, Construction and Maintenance of flow stations and underground storage</option>
                            <option value="LIP">Local and international procurement</option>
                            <option value="SSFP">Support services for projects</option>
                            <option value="CMSL">Civil and mechanical equipment supply and leasing</option>
                            <option value="HSEFPSMS">Health and safety environment and fire protection systems materials supply</option>
                            <option value="EFPSMS">Environment and fire protection systems materials supply</option>
                            <option value="SSS">Structural steel supply</option>
                            <option value="POCTG">Pipeline and oil country tubular goods (OCTG) supply </option>
                            <option value="WHCPS">Wellheads and control supply</option>
                            <option value="VFS">Valves and fittings supply</option>
                            <option value="PCFSS">Pumps, Compressor and fluid systems supply</option>
                            <option value="SSMPS">Strategic sourcing and man power supplies</option>
                            <option value="LSM">Logistics and supply chain management</option>
                            <option value="PM">Project Management</option>
                            <option value="FM">Facilities Management</option>
                        </select>
                        <div class="ol"><div class="nam" >Message</div><div id="rsik">*</div></div>
                        <div class="sd"><textarea name="comment" id="" cols="30" rows="10">Type your message here</textarea></div>
                    </div>
                    <button type="submit">Request A Quote</button>
                </form>
            </div>

This is my app.js file:

const express = require('express')
const path = require('path')
const app = express()
var mysql = require('mysql');
var bodyParser = require('body-parser')
const port = 3000

var urlencodedParser = bodyParser.urlencoded({ extended: false })

//Static Files
app.use(express.static(path.resolve(__dirname, 'public')))


//Set views
app.set('view engine', 'ejs')

app.set('views', './views')

app.get('/', (req, res) => {
  res.render('Home')
})

app.get('/About', (req, res) => {
  res.render('About')
})

app.get('/Projects', (req, res) => {
  res.render('Projects')
})

app.get('/RAQ', (req, res) => {
  res.render('RAQ')
})

app.get('/', (req, res) => {
  res.render('home', {qs: req.query});
})

app.post('/', urlencodedParser, (req, res) => {
  res.render('home', {qs: req.query});
})

app.get('/raq', (req, res) => {
  res.render('raq', {qs: req.query});
})
app.post('/raq', urlencodedParser, (req, res) => {
  res.render('raq', {qs: req.query});
})
var connection = mysql.createConnection({
  host     : 'https://www.blackanthemltd.site',
  user     : 'abayomi',
  password : '',
  database : 'subscribers'
});
 
connection.connect(function(err){
  if (err) throw err;
  console.log('connected..')
});

app.post('/', function(req,res){
  console.log(req.body);

  var sql ="insert into users values('"+req.body.fname+"','"+req.body.lname+"',"+req.body.email+")"
  connection.query(sql, function (error, results) {
    if (error) throw error;
    console.log('The solution is: ', results[0].solution);
  });

  res.render('Home', { title: 'Data Saved',
  message: 'Data Saved successfully.'})

  connection.end();
})

var connection2 = mysql.createConnection({
  host     : 'https://www.blackanthemltd.site',
  user     : 'abayomi',
  password : '',
  database : 'Quotation_requests'
});
 
connection2.connect(function(err){
  if (err) throw err;
  console.log('connected..')
});

app.post('/RAQ', function(req,res){
  console.log(req.body);

  var sql ="insert into users values('"+req.body.sfname+"', '"+req.body.slname+"', '"+req.body.semail+"', '"+req.body.services+"', "+req.body.comment+")"
  connection2.query(sql, function (error, results) {
    if (error) throw error;
    console.log('The solution is: ', results[0].solution);
  });

  res.render('RAQ', { title: 'Data Saved',
  message: 'Data Saved successfully.'})

  connection2.end();
})

app.listen(port, () => {
      console.log(`Example app listening at http://localhost:${port}`)
})


This is my package.json file on my remote server:

{
  "name": "balfyp",
  "version": "1.0.0",
  "description": "Final year project",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js"
  },
  "author": "abayomi",
  "license": "MIT",
  "dependencies": {
    "cors": "^2.8.5",
    "ejs": "^3.1.6",
    "express": "^4.17.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.12"
  }
}

this is my package.json file on my live server:

{
  "name": "balfyp",
  "version": "1.0.0",
  "description": "Final year project",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js"
  },
  "author": "abayomi",
  "license": "MIT",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "ejs": "^3.1.6",
    "express": "^4.17.1",
    "mysql": "^2.18.1",
    "nodemailer": "^6.6.3",
    "nodemailer-mailgun-transport": "^2.1.3"
  },
  "devDependencies": {
    "nodemon": "^2.0.12"
  }
}

Please what did I do wrong? I've done some changes to my codebase my webpage stopped displaying error and loaded fine which signifies that mysql connected successfully, but on clicking the submit button on my form after filling it I got the error:

Cannot POST /

here are the changes I made to the codebase particularly only to my app.js file:

const express = require('express')
    const path = require('path')
    const app = express()
    var mysql = require('mysql');
    var bodyParser = require('body-parser')
    const port = 3000
    
    var urlencodedParser = bodyParser.urlencoded({ extended: false })
    
    //Static Files
    app.use(express.static(path.resolve(__dirname, 'public')))
    
    
    //Set views
    app.set('view engine', 'ejs')
    
    app.set('views', './views')
    
    app.get('/', (req, res) => {
      res.render('Home')
    })
    
    app.get('/About', (req, res) => {
      res.render('About')
    })
    
    app.get('/Projects', (req, res) => {
      res.render('Projects')
    })
    
    app.get('/RAQ', (req, res) => {
      res.render('RAQ')
    })
    
    app.get('/', (req, res) => {
      res.render('home', {qs: req.query});
    })
    
    app.post('/', urlencodedParser, (req, res) => {
      res.render('home', {qs: req.query});
    })
    var connection = mysql.createConnection({
      host     : 'https://www.blackanthemltd.site',
      user     : 'root',
      password : 'Mynameisabayomi1.',
      database : 'bal'
    });
     
    connection.connect(function(err){
      if (err) throw err;
      console.log('connected..')
    });
    app.post('/', function(req,res){
      console.log(req.body);
    
      var sql ="insert into users values('"+req.body.fn+"','"+req.body.ln+"',"+req.body.email+")"
      connection.query(sql, function (error, results) {
        if (error) throw error;
        console.log('The solution is: ', results[0].solution);
      });
    
      res.render('Home', { title: 'Data Saved',
      message: 'Data Saved successfully.'})
    
      connection.end();
    })
    app.listen(port, () => {
          console.log(`Example app listening at http://localhost:${port}`)
    })

please how can I stop getting this error.

in flag
Is MySQL on the same server as the web host? Or is MySQL running on a separate server?
Abayomi Usman avatar
in flag
It's on the same server as the web host
Score:0
in flag

If MySQL is running on the same machine as the web server, then you do not need to modify anything with UFW. Instead, you will want to change your connection settings:

var connection = mysql.createConnection({
    host     : '127.0.0.1',
    user     : 'myWebApp',
    password : 'superSecretPassword!123.',
    database : 'bal'
});

Notes:

  1. The host value is generally 127.0.0.1 or localhost when the database is on the same system as the web server.
  2. You cannot (easily) use the root MySQL account for web applications anymore, so you will want to create a new account that has access to the database you’re using:
    1. Connect to MySQL on the server
      sudo mysql -u root
      
      Note: This is how the root MySQL account is accessed now. You need to have sudo privileges on the server. This is a security feature and one of the many reasons why web servers cannot use the root account anymore.
    2. Create a new account and grant it full access only to the database the website needs:
      CREATE USER 'baluser'@'localhost' IDENTIFIED WITH mysql_native_password BY 'superSecretPassword!123';
      GRANT ALL ON `bal`.* TO 'baluser'@'localhost';
      

This should give you what you need to get started.

Abayomi Usman avatar
in flag
Ok let me try this I hope it will work
Abayomi Usman avatar
in flag
Ok let me try this I hope it will work
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.