nodejs-express

Express

hello world

1
var express = require("express");
2
var http = require("http");
3
4
var app = express();
5
6
//middle ware 1
7
app.use(function (request, response) {
8
    console.log("In comes a request to: " + request.url);
9
    response.end("Hello World!");
10
});
11
//middle ware 2
12
...
13
//middle ware 3
14
...
15
16
http.createServer(app).listen(3000);
17
//same as app.listen(3000);

middleware

basic

1
app.use(function (req, res, next) {
2
    ...
3
    next();
4
});

error

1
app.use(function (err, req, res, next) {
2
    ...
3
    next();
4
});

third party middleware

logger

1
...
2
var logger = require("morgan");
3
app.use(logger("short");
4
...

express.static

1
...
2
var path = require("path");
3
var publicPath = path.resolve(__dirname, "public");
4
app.use(express.static(publicPath));
5
...

etc

  • connect-ratelimit
    • 시간당 특정 요청수 연결 조절
  • Helmet
    • http 헤더를 추가해 앱을 특정 종류의 공격으로부터 더 안전하게
  • cookie-parser
    • 브라우저 쿠키 분석
  • response-time
    • X-Response-Time 헤더를 전송, 애플리케이션의 성능 디버깅 가능
  • body-parser
    • 양식 제출할때 사용 등
  • compression
    • 바이트를 줄이기위해 응답 압축
  • connect-assets
    • CSS와 자바스크립트 자산을 컴파일하고 줄임
    • SASS, LESS, Stylus 등의 CSS 전처리기와 동작

      router

      basic

      1
      ...
      2
      //basic
      3
      app.get("/about", function (request, response) {
      4
          response.end("about");
      5
      });
      6
      //get variable, but not good
      7
      app.get("/hello/:who", function (request, response) {
      8
          response.end("Hello, " + request.params.who + "!");
      9
      });
      10
      //regex pattern and get variable
      11
      app.get(/^\/users\/(\d+)$/, function (req, res) {
      12
          var userId = parseInt(req.params[0], 10);
      13
          ...
      14
      });
      15
      //get query
      16
      app.get("/search", function (req, res) {
      17
          var b = req.query.q == "something like that";
      18
      });
      19
      ...

      routes

      app.js
      1
      var express = require("express");
      2
      var apiRouter = require("./routes/api_router");
      3
      4
      var app = express();
      5
      6
      app.use("/api", apiRouter);
      7
      8
      app.listen(3000);
      ./routes/api_router.js
      1
      var express = require("express");
      2
      3
      var api = express.Router();
      4
      api.use(function (req, res, next) {
      5
          ...
      6
          next();
      7
      });
      8
      api.get("/users", function (req, res) { ... });
      9
      api.post("/users", function (req, res) { ... });
      10
      api.get("/messages", function (req, res) { ... });
      11
      api.post("/messages", function (req, res) { ... });
      12
      13
      module.exports = api;

      response extend

      redirect
      1
      response.redirect("/some/path");
      2
      response.redirect("http://www.google.com/");
      sendFile
      1
      response.sendFile("/path/to/some_file.txt");
      json
      1
      response.json({ result: "blabla" });
      crud
      1
      app.get("/", function (req, res) { ... });
      2
      app.post("/", function (req, res) { ... });
      3
      app.put("/", function (req, res) { ... });
      4
      app.delete("/", function (req, res) { ... });
      send
      1
      app.send("message");

      ejs view

      Ejs view setup
      1
      var express = require("express");
      2
      var path = require("path");
      3
      4
      var app = express();
      5
      6
      //view files in ./views
      7
      app.set("views", path.resolve(__dirname, "views));
      8
      //set use ejs
      9
      app.set("view engine", "ejs");
      ./views/footer.ejs
      1
      </body>
      2
      </html>
      ./views/index.ejs
      1
      <!DOCUMENT html>
      2
      <html>
      3
          <head>
      4
              <meta charset="utf-8">
      5
              <title>Hello, world!</title>
      6
          </head>
      7
      <body>
      8
      <%= message =%>
      9
      <% include footer %>
      View render
      1
      app.get("/", function (req, res) {
      2
          response.render("index", {
      3
              message: "Hello World!"
      4
          });
      5
      });
Share