routes with express code example
Example 1: nodejs express routing get
const express = require('express');
const mysql = require('mysql');
const db = mysql.createConnection({
host: 'localhost',
user: 'yourusername',
password: 'yourpassword'
});
db.connect((error) => {
if(error) {
throw error;
}
console.log('MySQL Connected');
});
const app = express();
app.get('yourroute', (request, response) => {
let sql = 'SELECT * FROM yourtable';
let query = db.query(sql, (error, result) => {
if(error) {
throw error;
}
console.log(result)
})
});
app.listen('3000', () => {
console.log('Server is listening on port 3000');
});
Example 2: using multiple http verbs on express path request
app.route('/book')
.get(function (req, res) {
res.send('Get a random book')
})
.post(function (req, res) {
res.send('Add a book')
})
.put(function (req, res) {
res.send('Update the book')
})
Example 3: express route parameters
app.get('/',function(req,res)
{
res.send("Route path at base address");
});
Example 4: nodejs express routing
npm install --save mysql express
npm install -g nodemon