Express.js
-
Node.js frameworks
-
Intro to Express
-
Serving static files with Express
-
Templating Engines
-
Express routing and CORS
-
Middleware
-
Getting, Posting and Updating data
-
Database
Express
это минималистичный и гибкий веб-фреймворк для приложений Node.js, предоставляющий обширный набор функций для мобильных и веб-приложений
Meteor
является MVC фреймворком с открытым исходным кодом, с помощью которого вы можете создавать Web-приложения реального времени
Flatiron
это full-stack фреймворк который позволяет разработчикам создавать десктопные и мобильные приложения с повторно используемыми компонентами.
Locomotive
Locomotive позиционирует себя как один из самых мощных Node.js фреймворков, благодаря его поддержке паттерна MVC и REST принципов, а также безотказной работе с Express.
Koa
Команда разработчиков фреймворка Express.js создала еще один фреймворк под названием Koa.js — футуристический фреймворк следующего поколения для Node.js, который обещает быть более кратким и ярким, в сравнении с Express.js.
Hapi
Менее известный фреймворк, который разрабатывается командой Walmart Labs. В отличие от Express и Restify у него несколько другой подход, предоставляющий больший функционал сразу из коробки.
Sails
это MVC фреймворк, который позволяет легко и быстро создавать Node.js приложения. Sails.js лучше всего подходит для создания реалтаймовых приложений.
EXPRESS AT A HIGH LEVEL
- Based on Connect (a bit like Rack)
- De facto standard framework of node web apps
- Minimalistic, unopinionated
- Supports a variety of middleware
ROUTES
- Respond to HTTP requests with a callback
- Supports variable placement in routes
- Easy to serve JSON
MIDDLEWARE
- Some useful built in middleware (like bodyParser)
- Useful for preprocessing requests
- Authentication/Authorization
> npm install express --save
const express = require('express');
const app = express();
// Define the port to run on
app.set('port', 3000);
// Listen for requests
const server = app.listen(app.get('port'), () => {
const port = server.address().port;
console.log('Magic happens on port ' + port);
});
Генератор приложений Express
$ npm install express-generator -g
$ express -h
Usage: express [options][dir]
Options:
-h, --help output usage information
--version output the version number
-e, --ejs add ejs engine support
--hbs add handlebars engine support
--pug add pug engine support
-H, --hogan add hogan.js engine support
-v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
--git add .gitignore
-f, --force force on non-empty directory
$ express --view=pug myapp
create : myapp
create : myapp/package.json
create : myapp/app.js
create : myapp/public
create : myapp/public/javascripts
create : myapp/public/images
create : myapp/routes
create : myapp/routes/index.js
create : myapp/routes/users.js
create : myapp/public/stylesheets
create : myapp/public/stylesheets/style.css
create : myapp/views
create : myapp/views/index.pug
create : myapp/views/layout.pug
create : myapp/views/error.pug
create : myapp/bin
create : myapp/bin/www
.
├── app.js
├── bin
│ └── www
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
├── routes
│ ├── index.js
│ └── users.js
└── views
├── error.pug
├── index.pug
└── layout.pug
7 directories, 9 files
Serving static files with Express
app.use(express.static('public'));
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
app.use('/static', express.static('public'));
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html
Routes
app.METHOD(PATH, HANDLER)
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.post('/', (req, res) => {
res.send('Got a POST request');
});
app.put('/user', (req, res) => {
res.send('Got a PUT request at /user');
});
app.delete('/user', (req, res) => {
res.send('Got a DELETE request at /user');
});
Templating Engines
Runs through Jade complier
- Runs through Jade complier
- Operates as JavaScript
- Allows variables to be passed
- Minimalist Templating Engine
- Operates as JavaScript
- Allows variables to be passed
EJS
Middlewares
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware function in the stack.
Application-level middleware
var app = express()
app.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
});
app.use('/user/:id', function (req, res, next) {
console.log('Request Type:', req.method)
next()
});
app.get('/user/:id', function (req, res, next) {
console.log('ID:', req.params.id)
next()
}, function (req, res, next) {
res.send('User Info')
});
// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', function (req, res, next) {
res.end(req.params.id)
});
Router-level middleware
var app = express()
var router = express.Router()
// a middleware function with no mount path. This code is executed for every request to the router
router.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
router.use('/user/:id', function (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}, function (req, res, next) {
console.log('Request Type:', req.method)
next()
})
// a middleware sub-stack that handles GET requests to the /user/:id path
router.get('/user/:id', function (req, res, next) {
// if the user ID is 0, skip to the next router
if (req.params.id === '0') next('route')
// otherwise pass control to the next middleware function in this stack
else next()
}, function (req, res, next) {
// render a regular page
res.render('regular')
})
// handler for the /user/:id path, which renders a special page
router.get('/user/:id', function (req, res, next) {
console.log(req.params.id)
res.render('special')
})
// mount the router on the app
app.use('/', router)
Error-handling middleware
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
Built-in middleware
var options = {
dotfiles: 'ignore',
etag: false,
extensions: ['htm', 'html'],
index: false,
maxAge: '1d',
redirect: false,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now())
}
}
app.use(express.static('public', options))
Third-party middleware
var express = require('express')
var app = express()
var cookieParser = require('cookie-parser')
// load the cookie-parsing middleware
app.use(cookieParser())
CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT ,DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Database
var MongoClient = require('mongodb').MongoClient
MongoClient.connect('mongodb://localhost:27017/animals', function (err, db) {
if (err) throw err
db.collection('mammals').find().toArray(function (err, result) {
if (err) throw err
console.log(result)
})
})
Express.js
By Shuhratbek Mamadaliyev
Express.js
- 1,097