0

I'm wondering what would be the best route to populate a MySQL database with querys I pull from a script using express and node js.

The script I'm running on port 3000 looks like this:

curl localhost:3000/register?name=bob\&width=13.970000\&time=0
curl localhost:3000/wheels?left=0.000000\&right=0.000000\&time=0 --cookie "USER=bob"
curl localhost:3000/echo?dist=9.220000\&time=10 --cookie "USER=bob"
curl localhost:3000/line?l1=1\&l2=1\&l3=1\&time=20 --cookie "USER=bob"
curl localhost:3000/other?ir=0\&time=30 --cookie "USER=bob"
curl localhost:3000/wheels?left=3.000000\&right=3.000000\&time=100 --cookie "USER=bob"
curl localhost:3000/echo?dist=9.220000\&time=110 --cookie "USER=bob"
curl localhost:3000/line?l1=1\&l2=1\&l3=1\&time=120 --cookie "USER=bob"
curl localhost:3000/other?ir=0\&time=130 --cookie "USER=bob"
curl localhost:3000/wheels?left=3.000000\&right=3.000000\&time=200 --cookie "USER=bob"
curl localhost:3000/echo?dist=9.220000\&time=210 --cookie "USER=bob"
curl localhost:3000/line?l1=1\&l2=1\&l3=1\&time=220 --cookie "USER=bob"

My app.js file looks like this:

const express = require('express');
const cookieParser = require('cookie-parser');
const mysql = require('mysql');

let app = express()

app.use(cookieParser());

var pool = mysql.createPool( {
        host: 'localhost',
        user: 'root',
        password: 'root',
        database: 'cars',
        connectionLimit: 10,
        multipleStatements : true
});

app.get('/register', function(req, res) {
                mysql.pool.query("INSERT INTO todo (`name`) VALUES (?)", [name], function( err, results ) {
                        if (err)
                                throw err

                response.send(results);
                })
        });




app.listen(3000, function(req, res) {
        console.log('Express JS ready for port 3000');
});

My database is set up in phpMyAdmin and looks like this: My database using phpMyAdmin

When I run the script on port 3000, the error I keep getting is:

TypeError: Cannot read property 'query' of undefined

Eventually I want to populate the MySQL database using /wheels, /line, /echo, etc.. but the more I mess with it the more I get similar errors. Anyone see where I might be going wrong or can point me in the right as to where I might learn how to properly do something like this? Thanks

13
  • You don't need mysql.pool, just pool as it's declared as a variable Commented May 14, 2020 at 23:35
  • Thank you! Now the error I'm getting is: ReferenceError: name is not defined Commented May 14, 2020 at 23:43
  • Because name is a query parameter and not defined yet, you'd need req.query.name, Reference Error is usually solved by working out what's missing and/or incorrect. Debugging is useful and is a skill all programmers should have, once learnt, things like ReferenceErrors won't slow you down. Commented May 14, 2020 at 23:46
  • Debugging is very useful, it's a skill I'm familiar with when writing C++.. I just don't know node js or express that well. I've only finished a couple youtube tutorials and I'm still really lost. My campus is closed down so I have no where to get help besides on the internet for right now. I messed around with the app more and now when I run the script I'm getting "curl: (52) Empty reply from server" When all I did was change the query arguement to : pool.query("INSERT INTO cars (name) VALUES (?)", [req.query.name], function( err, results ) I also changed mysql db to be not strict Commented May 15, 2020 at 0:05
  • if you're good at debugging C++, it should be easily applied to Node.js and Express, the language shouldn't matter. In regard to the empty response, double check that results is defined using console.log, I'd assume it isn't so it's giving an empty response. Commented May 15, 2020 at 0:40

1 Answer 1

0
// file: server.js
const express = require('express');
const db = require('./db');
const app = express();

// you may wish to reconsider the use of .get at some stage
// what happens when you want to retrieve an item?
app.get('/models', (req, res) => {
  // learn about validation when you're comfortable with basics
  // this is especially important for public facing apps
  if (!req.query.manufacturer || !req.query.type || !req.query.cost) {
    return res.status(400).send('wrong input!'); // super helpful error messages
  }

  const public = req.query.public || true; // set defaults
  const { manufacturer, type, cost } = req.query;

  // when you're more comfortable, learn about abstractions + Service pattern
  // removing DB queries from route handlers, pushing the responsibility to a Service.
  db.query(
    'INSERT INTO car_models(manufacturer,type,cost,public) VALUES (?,?,?,?)',
    // learn about SQL injection, I **hope** the mysql package author considered it.
    [manufacturer, type, cost, public],
    (err, results) => {
      if (err) {
        console.error(err);
        return res.status(500).send('oh no');
      }

      return res.status(201).send(`Created ID: ${results.insertId}`);
    }
  );
});

app.listen(3000, () =>
  console.log('service started... accepting requests on http://localhost:3000')
);
/**
 *  File: db.js
 *  Responsibility: connect to MySQL
 *  Note: you could use an ORM here (**could** not always **should**)
 */
const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'develop',
  password: 'development',
  database: 'cars',
  port: 3306,
});

connection.connect((err) => {
  if (err) {
    console.error(`MySQL: Failed to connect to MySQL: ${err.message}`, err);
    return;
  }

  console.log('MySQL: Successfully connected to MySQL');

  connection.query(`CREATE TABLE IF NOT EXISTS car_models (
    id INT PRIMARY KEY AUTO_INCREMENT,
    manufacturer VARCHAR(30),
    type VARCHAR(10),
    cost BIGINT,
    public BOOLEAN
  );`);
});

module.exports = connection;

I had another example in mind, for the simplicity I've kept a style similar to yours, I hope this helps your understanding of it.

If there's anything you're unsure about, I recommend researching it. I don't recommend researching everything upfront. I tend to research things as/when I need them, or whenever I get the chance. (commuting for example)

You'll learn more through practice than researching, although it's important to find some form of balance. If not, you'll end up learning how to do something in a language and be restricted to only that language and only a small subset of the languages capabilities. (maybe, maybe not).

Adding a new car model is as simple as: curl http://localhost:3000/models?manufacturer=bmw&type=m3&cost=10000

Or, try opening http://localhost:3000/models?manufacturer=bmw&type=m3&cost=10000 in whatever browser you use (when it's running), and see what happens. You may find the browser (or Postman), will be easier to work with. Or you may not.

There's one very important part: no sessions, no cookies, no knowledge of the last request, nothing. This is stateless. For simple operations, there's no need to introduce such mechanisms as it's simply not required.

I'd suggest learning how Express.js can be structured (it's very flexible), there's patterns and best practices that you can follow, but maybe wait until you're comfortable with the language first, otherwise it can be a rabbit hole.

My final point, learn about the differences in stateless and stateful systems. Don't spend hours, take maybe 5 minutes so you understand the key concepts behind each. You can then use that knowledge to make your own decision about stateless vs stateful.

Something I wished I learned sooner: to solve a problem, you need to understand the problem you're trying to solve. Sounds basic, but I still get this wrong occasionally.

Good luck and all the best!

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

2 Comments

Thank you for this! I tried to re-engineer this to work with what I'm doing and I couldn't get anywhere with it really. It worked sort of like my first example did, but it wasn't creating new databases upon a table being filled out.. I'm going to post another update to the project here soon with what I've got. Right now, all I need to figure out is how to get node js/express to create a new data table once one is filled up.
Here's the updates I've made so far, hopefully they will give you a better idea of what I'm trying to achieve: stackoverflow.com/questions/61842957/…

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.