Express.js
https://gyazo.com/67d78cf80a80026aa97cbb58c9c1f445
公式
小さくて好き
ジェネレーター
code:express-gene.sh
npm i -g express-generator
// viewをpug app名をmyapp で生成
express --view=pug myapp
構成
Middleware
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
/req.params: { "userId": "34", "bookId": "8989" }
ルートハンドラー
注意
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()
詳しく
詳しく
Application (app)
app.get(name)
app.get(path,callback)
app.param(name,callback)
Request(req)
リクエスト本文で送信されたデータのキーと値のペアが含まれる
デフォルトでは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)
})
名前付きルート「パラメータ」にマップされたプロパティを含むオブジェクト
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'
});
非推奨なので、req.paramsかreq.bodyを使う
Response(res)
res.download(path,filename,option,func)
ファイルをpath「添付ファイル」として転送
ブラウザはユーザーにダウンロードを促す
code:res-download.js
res.download('/report-12345.pdf', 'report.pdf')
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' })
Router(router)
参考例
hr.icon
困りごと
データの受け渡し
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
}
ファイルアップロード
参考
hr.icon
2019/11/3