Require is not defined in console. node.js js mysql

I am trying to pass some coordinates from mysql database to be marked on a map but am having trouble getting them. i have looked at a number of similar questions on stackoverflow and have not been able to find an answer. Would appreciate if someone could please point out where i have gone wrong.

getListings.js

var mysql = require('mysql');

config = {
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'xx',
  port: 'xxxx',
};

var connection = mysql.createConnection(config); 
connection.connect(function (err) {
  if (err) {
    console.log('error connecting:' + err.stack);
  }
  console.log('connected successfully to DB.');

  connection.query('SELECT listing_coords FROM listings', (err, rows) => {
    if (err) throw err;

    console.log('Data received from Db:\n');
    var results = JSON.parse(JSON.stringify(rows));
    module.exports = { results };
    console.log(results);
  });
});

Then in my script.js file i have

var { results } = require('./getListings');
      console.log(results);

I am getting an error in the browser console saying "require is not defined"

I will need to figure out how to pull the coordinates from mysql in order to plot them, there has to be a way? Do i have to build an api and use ajax? Thanks in advance for any help.

have updated my getListings.js file – it now displays in the string of data i need in the browser as a raw data packet

var mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');

app.use(bodyparser.json());

config = {
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'xx',
  port: 'xxxx',
};

var connection = mysql.createConnection(config); //added the line
connection.connect(function (err) {
  if (err) {
    console.log('error connecting:' + err.stack);
  }
  console.log('connected successfully to DB.');

  app.listen(5000, () => console.log('express server is running at 5000'));

  app.get('/listings', (req, res) => {
    connection.query(
      'SELECT listing_coords FROM listings',
      (err, rows, fields) => {
        if (!err) res.send(rows);
        else console.log(err);
      }
    );
  });

I have been unsuccessful to get the output to run in script.js. I will post the working code when its working.

49 thoughts on “Require is not defined in console. node.js js mysql”

Leave a Comment