0

I am new to nodejs and mysql. I am having issues generating a list with data stored in MySQL. Everything else works fine, I would like to have the selection drop down of "Country" to be generated from whatever is in the MYSQL "test" table. This is as far as I got, in the future I would look to be adding more selection list with more data generated from MYSQL. I'm not sure what code to write to generate the loop to read the data from http://localhost:7002/getJson, or of this is even the way to go about it. Any assistance will be appreciated! Thank you

enter image description here routes.js

module.exports = function(app, passport) {
 app.get('/', function(req, res){
  res.render('index.ejs');
 });

 app.get('/login', function(req, res){
  res.render('login.ejs', {message:req.flash('loginMessage')});
 });

 app.post('/login', passport.authenticate('local-login', {
  successRedirect: '/profile',
  failureRedirect: '/login',
  failureFlash: true
 }),
  function(req, res){
   if(req.body.remember){
    req.session.cookie.maxAge = 1000 * 60 * 3;
   }else{
    req.session.cookie.expires = false;
   }
   res.redirect('/');
  });

 app.get('/signup', function(req, res){
  res.render('signup.ejs', {message: req.flash('signupMessage')});
 });

 app.post('/signup', passport.authenticate('local-signup', {
  successRedirect: '/profile',
  failureRedirect: '/signup',
  failureFlash: true
 }));

 app.get('/profile', isLoggedIn, function(req, res){
  res.render('profile.ejs', {
   user:req.user
  });
 });

 app.get('/logout', function(req,res){
  req.logout();
  res.redirect('/');
 })

 //-SQL QUERY
 var express = require('express')
  , http = require('http')
  , mysql = require('mysql'); // <---- HERE

 var app = express();

 var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: "password",
    database: 'test'
 });

 connection.connect(); // <---- AND HERE

 // all environments
 app.set('port', process.env.PORT || 7002);


 app.get('/getJson',function(req,res){
 connection.query('SELECT * FROM Country', function(err, rows, fields){
    if(err) {
        console.log(err); 
        res.json({"error":true});
    }
    else { 
        console.log(result); 
        res.json(result); 
    }
        console.log('Connection result error '+err);
            res.writeHead(200, { 'Content-Type': 'application/json'});
        res.end(JSON.stringify(rows));

    });

 } );

 http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
 });
 };

 //-SQL QUERY END



function isLoggedIn(req, res, next){
 if(req.isAuthenticated())
  return next();

 res.redirect('/');
}

server.js

var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var app = express();
var port = process.env.PORT || 8080;

var passport = require('passport');
var flash = require('connect-flash');

require('./config/passport')(passport);

app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
 extended: true
}));

app.set('view engine', 'ejs');

app.use(session({
 secret: 'justasecret',
 resave:true,
 saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());
app.use(flash());


require('./app/routes.js')(app, passport);

app.listen(port);
console.log("Port: " + port);

passport.js

var LocalStrategy = require("passport-local").Strategy;

var mysql = require('mysql');
var bcrypt = require('bcrypt-nodejs');
var dbconfig = require('./database');
var connection = mysql.createConnection(dbconfig.connection);

connection.query('USE ' + dbconfig.database);

module.exports = function(passport) {
 passport.serializeUser(function(user, done){
  done(null, user.id);
 });

 passport.deserializeUser(function(id, done){
  connection.query("SELECT * FROM users WHERE id = ? ", [id],
   function(err, rows){
    done(err, rows[0]);
   });
 });

 passport.use(
  'local-signup',
  new LocalStrategy({
   usernameField : 'username',
   passwordField: 'password',
   passReqToCallback: true
  },
  function(req, username, password, done){
    var fruit= req.body.fruit;
    var PhoneNumber= req.body.PhoneNumber;
    var Country= req.body.Country;
    var newUserMysql = {
          username: username,
          password: password,
          fruit: fruit,
          PhoneNumber: PhoneNumber,
          Country: Country,
         };

         var insertQuery = "INSERT INTO users (username, password, fruit, PhoneNumber, Country) values (?, ?, ?, ?, ?)";

         connection.query(insertQuery, [newUserMysql.username,newUserMysql.password, newUserMysql.closureplan,newUserMysql.UIR,newUserMysql.CSJ],
          function(err, rows){
           newUserMysql.id = rows.insertId;

           return done(null, newUserMysql);
          });

  })
 );

 passport.use(
  'local-login',
  new LocalStrategy({
   usernameField : 'username',
   passwordField: 'password',
   passReqToCallback: true
  },
  function(req, username, password, done){
   connection.query("SELECT * FROM users WHERE username = ? ", [username],
   function(err, rows){
    if(err)
     return done(err);
    if(!rows.length){
     return done(null, false, req.flash('loginMessage', 'No User Found'));
    }
    if(!bcrypt.compareSync(password, rows[0].password))
     return done(null, false, req.flash('loginMessage', 'Wrong Password'));

    return done(null, rows[0]);
   });
  })
 );
};

signup.js

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Login Register</title>
 <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
 <link rel="stylesheet" 
 href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
 <style>
  html{
   padding:50px;
  }
 </style>
</head>
<body>
 <div class="container">
  <div class="col-sm-6 col-sm-offset-3">
   <h2>Register</h2>

   <% if(message.length > 0) { %>
    <div class="alert alert-danger"><%= message %></div> 
   <% } %>

   <form action="/signup" method="post">
    <div class="form-group">
     <label>Username</label>
     <input type="text" class="form-control" name="username">
    </div>

    <div class="form-group">
     <label>Password</label>
     <input type="text" class="form-control" name="password">
    </div>

    <div class="form-group">
        <label>Select Fruit:</label>
            <select name="fruit" type="form" class="form-control">
              <option value="Apple">Apple</option>
              <option value="Orange">Orange</option>
              <option value="Banana">Banana</option>
            </select><br />


    </div>

    <div class="form-group">
        <label>Phone Number#</label>
        <input name="PhoneNumber" type="textbox" class="form-control" >
    </div>

    <div class="form-group">
        <label>Country</label>
        <select name="Country" type="form" class="custom-select">

       </select><br>
    </div>





    <button type="submit" class="btn btn-succcess btn-lg">Register</button>
   </form>

   <hr>

   <p>Need an account <a href="/signup">Register</a></p>
   <p>Go Back <a href="/">Home</a>.</p>
  </div>
 </div>
</body>
</html>

database.js

module.exports = {
 'connection':{
  'host':'localhost',
  'user':'root',
  'password':'password'
 },
 'database':'signup',
 'user_table':'information',

}

enter image description here

0

1 Answer 1

1

In your front end code you GET /getJSON which returns a JSON object. Then you need to append the elements to your <select> tag as <option>s

fetch('https://jsonplaceholder.typicode.com/todos')
  .then(response => response.json())
  .then(json => {
    console.log(json);
    let select = document.getElementById("test");
    json.forEach(e=>{
      var opt1 = document.createElement("option");
      opt1.text = e.title;
      opt1.value = e.id;
      select.add(opt1);
    });
    
  })
  
<select id="test">
</select>

Sign up to request clarification or add additional context in comments.

10 Comments

generally people serve their javascript in a /public/scripts/ folder and then in the html they use a <script src="/public/scripts/index.js">/<script> type of deal
for testing you can also just put it right in the ejs/html inside a <script></script> tag
When I am trying to go to I get localhost:7002/getJsonError [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. Is that correct? Is let select = document.getElementById("test"); is that the table name? and opt1.text = e.title; opt1.value = e.id; are the columns?
Cannot set headers after they are sent to the client --- this is an error in your /getJson route possibly
Remove the lines console.log('Connection result error '+err); res.writeHead(200, { 'Content-Type': 'application/json'}); res.end(JSON.stringify(rows)); from your /getJson
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.