Express.js
https://gyazo.com/67d78cf80a80026aa97cbb58c9c1f445
Node.jsのための高速で、革新的な、最小限のWebフレームワーク
公式
Express - Node.js web application framework
日本語
小さくて好き
ジェネレーター
code:express-gene.sh
npm i -g express-generator
// viewをpug app名をmyapp で生成
express --view=pug myapp
構成
express実践入門-構成の
Middleware
基本的にMiddleware ミドルウェアで足りないものを補完していく
Routing
Express routing
よく使う
router.get()
router.post()
ルートパス
ルートの中身は、正規表現で表現可能
code:route-path.js
// aがついたルート
router.get(/a/, function (req, res) {
res.send('/a/')
})
ルートパラメーター
code:route-param.js
router.get('/users/:userId/books/:bookId', function (req, res) {
res.send(req.params)
})
//example
/Route path: /users/:userId/books/:bookId
/Request URL: http://localhost:3000/users/34/books/8989
/req.params: { "userId": "34", "bookId": "8989" }
ルートハンドラー
コールバック関数 callbackでルート処理可能に
注意
next が必要
code:route-handler.js
var cb0 = function (req, res, next) {
console.log('CB0')
next()
}
var cb1 = function (req, res, next) {
console.log('CB1')
next()
}
router.get('/example/d', cb0, cb1, function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from D!')
})
hr.icon
API reference
必要、大事なもののみメモ
express()
Express 4.x express()
Express 4.x express.json()
詳しく
Express 4.x express.urlencoded()
詳しく
Application (app)
Express 4.x app
Express 4.x - app.get()
app.get(name)
app.get(path,callback)
Express 4.x app.param()
app.param(name,callback)
Express 4.x app.post()
Express 4.x app.render()
Express 4.x app.set()
Express 4.x app.use()
Request(req)
Express 4.x req
Express 4.x req.body()
リクエスト本文で送信されたデータのキーと値のペアが含まれる
デフォルトではundefined
express.json()や express.urlencoded()などのボディ解析ミドルウェアを使用するときに設定される
code:req-body.js
var express = require('express')
var app = express()
app.use(express.json()) // for parsing application/json
// for parsing application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }))
app.post('/profile', function (req, res, next) {
console.log(req.body)
res.json(req.body)
})
Express 4.x req.params()
名前付きルート「パラメータ」にマップされたプロパティを含むオブジェクト
code:req-params.js
router.get('/name/:name_text', function(req, res, next) {
// GET /user/name/name_text
console.log(req.params.name_text);
res.send(req.params.name_text);
// => 'name_text'
});
Express 4.x req.param()
非推奨なので、req.paramsかreq.bodyを使う
Response(res)
Express 4.x res.download()
res.download(path,filename,option,func)
ファイルをpath「添付ファイル」として転送
ブラウザはユーザーにダウンロードを促す
code:res-download.js
res.download('/report-12345.pdf', 'report.pdf')
Express 4.x res.json()
res.json(body)
JSON応答を送信
JSON.stringify()を使用してJSONストリングに変換されたパラメーター送信
任意のJSONタイプ:
オブジェクト、配列、文​​字列、ブール値、数値、またはnull
他の値をJSONに変換するためにも使用可能
code:res-json.js
res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })
Express 4.8.0~ res.sendFile()
Router(router)
実装例
GitHub.iconKiichiSugihara/express-rest-api: REST API by express.js
GitHub.iconKiichiSugihara/vue-login: JWT Auth Project by Vue.js & Express& MongoDB
参考例
GitHub.iconFull-Stack-React-Projects-Second-Edition/Chapter03 and 04/mern-skeleton/server at master · KiichiSugihara/Full-Stack-React-Projects-Second-Edition
Controller コントローラなどの分け方が綺麗
hr.icon
困りごと
データの受け渡し
ファイルダウンロード Node.js→ブラウザへ
code:router.js
router.post
const data = {"name":"azraq","country":"egypt"};
const json = JSON.stringify(data);
const filename = 'user.json';
const mimetype = 'application/json';
res.setHeader('Content-Type', mimetype);
res.setHeader('Content-disposition','attachment; filename='+filename);
res.send( json );//json表示
render
}
参考javascript - Download file from Json object in Node.js - Stack Overflow
ファイルアップロード
参考
✅チュートリアル: JavaScript SDK を使用して Node.js Web アプリをビルドして Azure Cosmos DB SQL API データを管理する | Microsoft Docs
hr.icon
2019/11/3