Skip to content

Instantly share code, notes, and snippets.

@Tjoosten
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tjoosten/9f71f1e4225ba3e8daee to your computer and use it in GitHub Desktop.
Save Tjoosten/9f71f1e4225ba3e8daee to your computer and use it in GitHub Desktop.
NodeJS
// error = Cannot GET /api/Bears
// Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'newuser'@'127.0.0.1' (using password: YES)
// Server.js
// BASE SETUP
// =======================================================================================
// Call the packages we need
var express = require('express'); // call express
var app = express(); // define app using express
var bodyParser = require('body-parser');
var mysql = require('mysql'); // Gets mysqyl driver for the API
// Configure app to use bodyParser()
// This will let us get the data form a POST
app.use(bodyParser.urlencoded( { extended: true} ));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // Server port
// Setup MySQL connection
var connection = mysql.createConnection({
host: 'localhost',
user: 'newuser',
password: '2fU3g5Yn',
database: 'Regimenten',
});
// Routes for the API
// ========================================================================================
var router = express.Router(); // get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next) {
//
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.get('/Military-deaths', function(reg, res) {
// Connect to DB
connection.connect();
// Query
var Query = 'SELECT * FROM Regiment';
connection.query(Query, function(err, rows, fields) {
if (err) throw err;
for (var i in rows) {
console.log('Post Titles: ', rows[i].Geboorte_datum);
}
});
});
// Test rout to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(reg, res) {
res.json({ message: 'Hooray! Welcome to McRea API!'});
});
// More routes for the API will happen here
// REGISTER OUR ROUTES ---------------------------------------------------------------------
// All of our routes will be prefixed with /api
app.use('/api', router);
// BEAM THE SERVER UP
// =========================================================================================
app.listen(port);
console.log('Magic happens on port' + port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment