theamateurdataanalyst
theamateurdataanalyst

Reputation: 2834

Using node.js, express, and MySQL

I am currently in the process of creating an app and I am using node.js, express, and MySQL. I feel that I am in a bit of a rut in connecting my server to my database. Here's how I see things so far

server.js

var express = require('express');
var app = express();

//These are just my static finals so this can be ignored for now
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/public/views'));
app.use(express.static(__dirname + '/public/controlers'));

app.listen(3000);

console.log("Listening at 3000")

Here I am setting up a local server on my computer that is listening on port 3000. What I am hoping to do here eventually is handle post requests. My goal is to ensure that post requests are inserted into the database. So I realize that I need to do two things create a database and a schema for my database. For now I just want to create a simple table with an ID and first_name columns. I am using this driver https://github.com/felixge/node-mysql/.

So my next step is creating a connection

dbconnection.js

var mysql = require('mysql')
var app = require('../server.js');

var connection = mysql.createConnection({
    host        : 'localhost',
    port        :  3000,
    user        : 'username',
    password    : 'password',
    database    : 'liveDatabase'
});

connection.connect()
//queries and error handling go here
connection.end()

This is where I lose touch with my program.

Here's what I don't understand:

Any help is appreciated. Thanks!

Upvotes: 0

Views: 227

Answers (1)

Trott
Trott

Reputation: 70183

This is just a start, but this seems to be the crux of the misunderstanding:

  • Your server.js is creating a web server that listens on port 3000. Your dbconnection.js is trying to connect on that server on port 3000. That's not right. You want it to connect to your MySQL server instead.

  • It seems more logical for server.js to require dbconnection.js rather than the other way around. Then server.js can send/receive info with the database via the required module.

Upvotes: 1

Related Questions