Last active
February 13, 2019 03:41
-
-
Save bbachi/c210d96b2d9fc3fb9c8ae2aa217eae99 to your computer and use it in GitHub Desktop.
How to write production ready Node.js Rest API With javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require("express"), | |
bodyParser = require("body-parser"), | |
app = express(), | |
port = 3070; | |
// array to hold users | |
const users = [{firstName:"fnam1",lastName:"lnam1",userName:"username1"}]; | |
app.use(bodyParser.json()); | |
// Default user | |
app.get("/", function(req, res) { | |
res.send("App works!!"); | |
}) | |
// request to get all the users | |
app.get("/users", function(req, res) { | |
res.json(users); | |
}) | |
// request to get all the users by userName | |
app.get("/users/:userName", function(req, res) { | |
let user = users.filter(function(user){ | |
if(req.params.userName === user.userName){ | |
return user; | |
} | |
}) | |
res.json(user); | |
}) | |
// request to post the user | |
// req.body has object of type {firstName:"fnam1",lastName:"lnam1",userName:"username1"} | |
app.post("/user", function(req, res) { | |
users.push(req.body); | |
res.json(users); | |
}) | |
app.listen(port, function(err) { | |
console.log("running server on from port:::::::" + port); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "user_api", | |
"version": "1.0.0", | |
"description": "sample rest api", | |
"main": "index.js", | |
"scripts": { | |
"start": "node index.js", | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "Bhargav Bachina", | |
"license": "ISC", | |
"dependencies": { | |
"body-parser": "^1.18.3", | |
"express": "^4.16.4" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment