TIL Day 33 Express framework
31209 ワード
リファレンス
https://expressjs.com/ko/
Expressバー
高速実行方法
mkdir 폴더이름
cd 폴더이름
// 폴더로 들어감
npm init
//package.json 파일 생성
npm install express --save
npm install express
Expressの基本形態
const express = require('express') //express 불러옴
const app = express() //express를 실행한 객체를 app에 할당
const port = 3000 //3000번 포트 설정
app.get('/', (req, res) => { //app에 get + 엔드포인트가 '/'인 요청이 올 때 'Hello World'를 리턴한다.
res.send('Hello World!')
})
app.listen(port, () => { //app에 3000번 포트를 연결
console.log(`Example app listening at http://localhost:${port}`)
})
デフォルトのルーティング
きほんこうぞう
app.METHOD(PATH, HANDLER)
//app : express의 인스턴스
//method : HTTP 요청 메소드
//path : 서버에서의 경로
//handler : 라우트가 일치할 때 실행되는 함수
ex)app.get('/', function (req, res) {
res.send('Hello World!');
});
app.post('/', function (req, res) {
res.send('Got a POST request');
});
app.put('/user', function (req, res) {
res.send('Got a PUT request at /user');
});
app.delete('/user', function (req, res) {
res.send('Got a DELETE request at /user');
});
ルート
ルーティングのデフォルトの例
var express = require('express');
var app = express();
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function(req, res) {
res.send('hello world');
});
ルーティングパス
app.get('/', function (req, res) {
res.send('root');
});
app.get('/about',function(req,res){
res.send('about')
})
app.get('/random.text',function(req,res){
res.send('random.text')
})
ルーティングマネージャ
app.get('/example/b', function (req, res, next) {
console.log('the response will be sent by the next function ...');
next(); //다음 콜백함수를 연결
}, function (req, res) {
res.send('Hello from B!');
});
ex)コールバック関数配列がルーティングを処理するvar cb0 = function (req, res, next) {
console.log('CB0');
next();
}
var cb1 = function (req, res, next) {
console.log('CB1');
next();
}
var cb2 = function (req, res) {
res.send('Hello from C!');
}
app.get('/example/c', [cb0, cb1, cb2]);
ex)独立関数と配列の組み合わせによるルーティングvar cb0 = function(req,res,next){
console.log('CB0')
next();
}
var cb1 = function(req,res,next){
console.log('CB1')
next();
}
app.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!')
})
レスポンスメソッド
メソッド説明res.end()応答プロセスは、res.json()JSON応答送信res.send()を8ビットストリームで送信するres.sendFile()ファイルの送信を終了する
app.route()
app.route('/book')
.get(function(req, res) {
res.send('Get a random book');
})
.post(function(req, res) {
res.send('Add a book');
})
.put(function(req, res) {
res.send('Update the book');
});
express.Router
//bird.js에 작성
var express = require('express');
var router = express.Router();
// middleware that is specific to this router
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
// define the home page route
router.get('/', function(req, res) {
res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
res.send('About birds');
});
module.exports = router;
//기본 라우터 설정
var bird = require('./birds')
app.use('/birds',birds)
// /birds로 끝나는 엔드포인트를 입력할 경우 birds.js로 이동
Expressアプリケーション用のミドルウェアの作成
通常はnextの名前で変数を作成します.
var express = require('express');
var app = express();
//미들함수 생성
var requestTime = function (req, res, next) {
req.requestTime = Date.now();
next(); //다음 미들함수를 호출
};
app.use(requestTime); //미들함수를 지정하여 호출하는 함수
//미들웨어의 로드 순서는 중요하며, 먼저 로드되는 미들웨어 함수가 먼저 실행된다.
//루트 경로에 대한 라우팅 이후에 myLogger가 로드되면, 루트 경로의 라우트 핸들러가 요청-응답 주기를 종료하므로 요청은 절대로 myLogger에 도달하지 못하며 앱은 “LOGGED”를 인쇄하지 않된다..
app.get('/', function (req, res) {
var responseText = 'Hello World!';
responseText += 'Requested at: ' + req.requestTime + '';
res.send(responseText);
});
app.listen(3000);
Reference
この問題について(TIL Day 33 Express framework), 我々は、より多くの情報をここで見つけました https://velog.io/@boo1996/TIL-Day-33-Express-frameworkテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol