nodejs api with mysql code example
Example 1: use nodejs mysql
var mysql = require('mysql');var connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret', database : 'my_db'}); connection.connect(); connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) { if (error) throw error; console.log('The solution is: ', results[0].solution);}); connection.end();
Example 2: 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');
// connection configurations
const mc = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'mydb'
});
// connect to database
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'); //importing route
routes(app); //register the route