Skip to main content

Create Nodejs Server for HTTP requests


a) Install nodejs
b) Prepare for Node js server,
Create base structure
mkdir myappnode
cd myappnode
npm init       (accept all defaults, creates package.json)

npm install --save express body-parser


Create route base structure
mkdir app
cd app
mkdir routes
cd routes

Add HTTP GET method support

vi myapp_routes.js
module.exports = function(app, db) {
  app.get('/myapp', (req, res) => {
    res.send('Hello from myapp, GET method')
  });
};


Create new index.js (/app/routes/index.js)

const noteRoutes = require('./myapp_routes');
module.exports = function(app, db) {
  noteRoutes(app, db);
  

};

Update server.js 

cd ../..
vi server.js
const express        = require('express');
const app            = express();
const port = 9000;

require('./app/routes')(app, {});
app.listen(port, () => {
  console.log('Server running on' + port);
});

Start server.js 
node server.js

Test using webbrowser 
http://localhost:9000/myapp

Output : Hello from myapp, GET method


ADDITIONAL CODE TO CONNECT TO mysql

1. Install mysql module

npm install --save mysql

2. Modify 

vi app/routes/myapp_routes.js 

module.exports = function(app, db) {
  app.get('/myapp', (req, res) => {
    res.send('Hello from myapp, GET method')
  });
};

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "root"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});

3. Test

node server.js

4. Output
Server running on9000
Connected!



Code to select data from the Table
var express = require('express');
var app = express();
var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'root',
  database : 'DBNAME'
});

module.exports = function(app, db) {
  app.get('/myapp', (req, res) => {

 connection.query('select * from TABLE where ID = 2001', function (error, results, fields) {
    if (error) throw error;
    res.send(results[0]);
  });

  });

};


Comments