Building REST APIs using NodeJS

Onejohi
Onejohi
Mar 9, 2018 · 4 min read

Using Express

var express = require("express");
var app = express();
app.use("/", (req, res, next) => {
res.json({
ok: true,
data: "Hello world"
});
}):
app.listen(process.env.PORT || 3000, () => {
console.log("Server running on port 3000");
});
{
"ok": true,
"data": "Hello world"
}

Introducing routes

var express = require("express");
var router = express.Router();
//get
router.get("/", (req, res, next) => {
res.json({
ok: true,
data: "Index get"
});
});
//post
router.post("/", (req, res, next) => {
var username = req.body.username;
var password = req.body.password;
var user = {
username: username,
password: password
};
res.json({
ok: true,
userInfo: user
});
});
module.exports = router;

Body Parser Middleware

var express = require("express");
var bodyParser = require("body-parser");
var app = express();
//use the body parser middleware in express
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false });
//routing to index.js file in the routes folder
app.use("/", require("./routes/index");
app.listen(process.env.PORT || 3000);

Run.

Onejohi

Written by

Onejohi

Creative 🚀 | Gamer 🎮 | Web & App developer 💻📱 | Graphics Designer 📏📝 | Entrepreneur 💶 | Cool AF 😎🤓 https://onejohi.herokuapp.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade