В этой статье вы увидите, как легко создать REST API в node.js, используя платформу Express . Предварительные условия для этого руководства — базовые знания по node.js и базовое понимание архитектуры REST. Вам не нужно никаких специальных знаний.
Сначала мы создадим папку приложения узла, имя нашего приложения будет общим, как и имя папки.
$ mkdir share
$ cd share
Теперь мы можем создать наше приложение узла с помощью команды npm init .
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (share)
version: (1.0.0)
description: Sample RestApi
entry point: (index.js) app.js
test command:
git repository:
keywords:
author: dursun
license: (ISC)
About to write to /Users/dursun/workspaces/dzone/myArt/share/package.json:
{
"name": "share",
"version": "1.0.0",
"description": "Sample RestApi",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "dursun",
"license": "ISC"
}
Is this ok? (yes) yes
Следующим шагом является добавление экспресс-фреймворка и body-parser в наш проект.
$ npm install express --save
npm WARN package.json share@1.0.0 No repository field.
npm WARN package.json share@1.0.0 No README data
express@4.13.3 node_modules/express
├── escape-html@1.0.2
├── merge-descriptors@1.0.0
├── cookie@0.1.3
├── array-flatten@1.1.1
├── cookie-signature@1.0.6
├── utils-merge@1.0.0
├── content-type@1.0.1
├── vary@1.0.1
├── range-parser@1.0.2
├── content-disposition@0.5.0
├── fresh@0.3.0
├── path-to-regexp@0.1.7
├── serve-static@1.10.0
├── methods@1.1.1
├── etag@1.7.0
├── parseurl@1.3.0
├── depd@1.0.1
├── qs@4.0.0
├── on-finished@2.3.0 (ee-first@1.1.1)
├── finalhandler@0.4.0 (unpipe@1.0.0)
├── debug@2.2.0 (ms@0.7.1)
├── proxy-addr@1.0.8 (forwarded@0.1.0, ipaddr.js@1.0.1)
├── accepts@1.2.13 (negotiator@0.5.3, mime-types@2.1.7)
├── type-is@1.6.8 (media-typer@0.3.0, mime-types@2.1.7)
└── send@0.13.0 (destroy@1.0.3, statuses@1.2.1, ms@0.7.1, mime@1.3.4, http-errors@1.3.1)
$ npm install body-parser --save
npm WARN package.json share@1.0.0 No repository field.
npm WARN package.json share@1.0.0 No README data
body-parser@1.14.0 node_modules/body-parser
├── bytes@2.1.0
├── content-type@1.0.1
├── depd@1.1.0
├── qs@5.1.0
├── iconv-lite@0.4.11
├── on-finished@2.3.0 (ee-first@1.1.1)
├── http-errors@1.3.1 (statuses@1.2.1, inherits@2.0.1)
├── raw-body@2.1.3 (unpipe@1.0.0)
├── debug@2.2.0 (ms@0.7.1)
└── type-is@1.6.8 (media-typer@0.3.0, mime-types@2.1.7)
Прежде чем мы начнем кодирование, давайте взглянем на наш файл package.json, он должен выглядеть следующим образом;
{
"name": "share",
"version": "1.0.0",
"description": "Sample RestApi",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "dursun",
"license": "ISC",
"dependencies": {
"express": "^4.13.3"
}
}
Теперь пришло время создать наш входной файл приложения app.js,
var express = require('express'),
bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
var shareRouter = express.Router();
var db = [];
shareRouter.route('/')
.get(function(req, res) {
res.status(200).json(db);
})
.post(function(req,res){
db.push(req.body);
res.status(200).json(db);
});
app.use('/api/share', shareRouter);
app.listen(8080, function(){
console.log('Application started.');
})
module.exports = app;
В строке 1 и 2 включены интегрированные среды, в строке 4 создано экспресс- приложение, а в строке 24 приложение начало прослушивание.
От строки 6 до 22 приложение настроено. В строке 22 мы перенаправили все запросы, сделанные по URL / api / share , на shareRouter . В shareRouter ручки и GET , и почтовые запросы на GET запросов , которые мы просто вернуть дб объект. Для почтовых запросов мы добавили объект, указанный в теле. кстати, тело запроса post анализируется в json с помощью экспресс-парсера тела промежуточного программного обеспечения, который добавляется в строке 6.
Запустите приложение и проверьте API:
$ node app.js
Application started.
Мы будем использовать почтальон для проверки нашего API следующим образом;