connect to mysql from express api code example
Example 1: rest api node js with mysql
const express = require('express'),
app = express(),
bodyParser = require('body-parser');
port = process.env.PORT || 3000;
const mysql = require('mysql');
const mc = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mydb'
});
mc.connect();
app.listen(port);
console.log('API server started on: ' + port);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./app/routes/approutes');
routes(app);
Example 2: how to access a database in express
var MongoClient = require('mongodb').MongoClient
MongoClient.connect('mongodb://localhost:27017/animals', function (err, client) {
if (err) throw err
var db = client.db('animals')
db.collection('mammals').find().toArray(function (err, result) {
if (err) throw err
console.log(result)
})
})