Get MySQL Data Using ExpressJS

Before Started:

  • Node.js already installed
  • ExpressJS already installed using “npm install –save express”
  • MySQL module already installed “npm install –save mysql”


  • Database Name : projek_inventory
  • Table Name : table_stock_in

Data displayed in below table:

110 2019-09-15 20:28:10
220 2019-09-16 20:28:10
330 2019-09-17 20:28:41


If i go to “http://localhost:3000/data_stock_masuk” then i want to get result like below format:


How to make this … ?


We need 2 steps, namely:

  • Create dbConfig.js for create database configuration
  • Create index.js for the main file

Create dbConfig

Create dbConfig.js and add this code below:

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "projek_inventory"

con.connect(function(err) {
    if (err) throw err;
    console.log("Koneksi berhasil");



  • var mysql = require(‘mysql’), this code mean we import mysql module and give it to mysql variable
  • module.exports=con, this code mean we export con variable as a module

Create index.js

Create index.js filename and add this code:

var express = require('express');
var app = express();

var koneksi = require('./dbConfig.js');
app.get("/data_stock_masuk", function(req, res){
	koneksi.query("SELECT * FROM table_stock_in limit 3", function (err, result, fields) {
    if (err) throw err;


  • var express = require(‘express’), this code means that we import express module and give it to express variable, we use this variable to create application
  • require(‘./dbConfig.js’), this code mean we import dbConfig.js file, so later we can execute all code inside it
  • app.get(“/data_stock_masuk”, function(req, res){ }), this code means if the app get request from “http://localhost:3000/data_stock_masuk” then execute the code inside function
  • koneksi.query(), this code for data query
  • res.send({“data_stock”:result}), this code is for sending response


Start mysql service

Run your file with this command below:

node index.js

Then open your browser and type “http://localhost:3000/data_stock_masuk”

Thanks for reading

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *