Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Find out more here.
I will create a simple REST API using Express.js. A Representational State Transfer (REST) interface provides a set of operations that can be invoked by a remote client over a network, using the HTTP protocol.
Before we proceed, we must ensure that we have Nodejs installed.
Create directory and navigate to the created directory.
$ mkdir api
$ cd api
We are going to use the ExpressJs nodeJs framework to create our API, so run the code below in your terminal:
npm install express --save
npm install body-parser --save
We need to create an API entry point app.js (or anything you want). Now we will create an app.js file.
var express = require("express");
var bodyParser = require("body-parser");
var routes = require("./routes/routes.js");
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
routes(app);
var server = app.listen(3000, function () {
console.log("app running on port.", server.address().port);
});
The two lines below tell express to accept both JSON and url encoded values
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
We defined the port where our server should be running. Also you can define port anything you want.
var server = app.listen(3000, function () {
console.log("app running on port.", server.address().port);
});
Now we will install faker. Run this command:
npm install faker --save
Now we can edit our routes.js:
var faker = require("faker");
var appRouter = function (app) {
app.get("/", function (req, res) {
res.status(200).send({ message: 'Welcome to API' });
});
app.get("/user", function (req, res) {
var data = ({
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
});
res.status(200).send(data);
});
app.get("/users/:num", function (req, res) {
var users = [];
var num = req.params.num;
if (isFinite(num) && num > 0 ) {
for (i = 0; i <= num-1; i++) {
users.push({
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
});
}
res.status(200).send(users);
} else {
res.status(400).send({ message: 'what is your name' });
}
});
}
module.exports = appRouter;
Now you can hit the route http://localhost:3000/users/1.
Imagine that we have thousands of images inside of a...
def get_ref_face(self, ref_image_path):
try:
Sometimes you need a number of words for a certain...
var iTotalWords = $(this).text().split(' ').length;
Designed & Built by Mijo Kristo