LoginSignup
0
0

Node.js のExpressで学ぶミドルウェア

Posted at

ミドルウェア

ミドルウェアって何?

  • コンピュータの分野で、コンピュータの基本的な制御を行うOSと書く業務処理を行うアプリケーションソフトウェアとの中間に入るソフトウェアのこと
  • ある特定の分野に属するアプリケーションに対して、その分野に共通する機能や処理をアプリケーションに提供する

ググった結果、以上の説明がなされるが、あまり理解できない。

毎回行っている同一の処理を共通化し、再利用するためのしくみ

という説明に納得した。

sample.js
const express=require('express'),
app=express();

const logger=require('morgan');

app.use(logger('dev'));
app.use(function(req,res,next){
    console.log('this is middleware');
    next();
})

app.get('/hello',function(req,res){
    res.send('Hello World");
});

app.get('/bye',function(req,res){
    res.send('Good bye');
});

app.listen(8080);
console.log('server listen ...');

  • ここでは、app.useの部分がミドルウェアの役割を果たしている
  • /hello にアクセスしても、/byeにアクセスしても、
    HTTPリクエストをした際のアクセスログと、自作した「this is middleware」という表示がログとして出力される

image.png

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0