ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Express Routes
    Node.js/Express 2021. 11. 14. 00:00

    이 글은 Express를 이용해 Basic CRUD API를 구현하기 위해
    필요한 개념 및 문법을 정리하기 위해 작성하였습니다.




    < Introduction >

    Express is a powerful but flexible Javascript framework for creating web servers and APIs. It can be used for everything from simple static file servers to JSON APIs to full production servers.

    You will be learning all the necessary skills to implement an API allowing clients to Create, Read, Update, and Delete Data. These four functionalities together are known as
    CRUD, and they form the backbone of many real-life APIs.

     

     


    < Starting a Server >

    To make and start Server!

    The purpose of a server is to listen for requests, perform whatever action is required to satisfy the request, and then return a response.

     

    1. Express is a Node module, so in order to use it, we will need to import it into our program file.
    const express = require('express');​

    2. To create a server, the imported express function must be invoked.
    const app = express();​
    : It returns an instance of an Express application.

    3. In order for our server to start responding, we have to tell the server where to listen for new requests by providing a method called app.listen( ).
    const PORT = 4001;
    app.listen(PORT, () => {
      console.log(`Server is listening on port ${PORT}`);
    });​

    first argument : a port number (Where to listen for new requests)
    second argument : callback function that will be called once the server is running and ready to receive responses.

     

     

     


    < Writing Your First Route >

    Once the Express server is listening, it can respond to any and all requests. But how does it know what to do with these requests? To tell our server how to deal with any given request, we register a series of routes. Routes define the control flow for requests based on the request’s path and HTTP verb.

     

    • Express Routes usually take two arguments, a path (usually a string), and a callback function to handle the request and send a response.
    • The path is the part of a request URL after the hostname and port number, so in a request to localhost:4001/monsters, the path is /monsters (in this example, the hostname is localhost, the port number is 4001).
    • The HTTP verb is always included in the request, and it is one of a finite number of options used to specify expected functionality.

     

    ex)

    app.get('/moods', (req, res, next) => {
      // Here we would send back the moods array in response
    });

    : The route above will match any GET request to '/moods' and call the callback function, passing in two objects as the first two arguments. These objects represent the request sent to the server and the response that the Express server should eventually send to the client.

    (if no routes are matched, Express server will send a 404 Not Found response to the client.)

     

     


    < Sending a Response >

    HTTP follows a one request-one response cycle.

    Express servers send responses using the .send( ) method on the response object.

     

    • .send( ) takes any input and include it in the reponse body.

     

    ex)

    const monsters = [
      { type: 'werewolf' }, 
      { type: 'hydra' }, 
      { type: 'chupacabra' }
    ];
    app.get('/monsters', (req, res, next) => {
      res.send(monsters);
    });

     

     


    < Routes Parameters >

    Express servers provide Routes Parameters to use routes dynamically.

     

    • Parameters are route path segments that begin with in their Express route definitions. They act as wildcardsmatching any text at that path segment.
      For example, '/monsters/:id' will match both '/monsters/1' and '/monsters/45'
    • Express parses any parameters, extracts their actual values, and attaches them as an object to the request object: req.params.
      - Object’s key : any parameter names in the route,
      - Object's key’s value : actual value of that field per request.

     

    const monsters = { 
      hydra: { height: 3, age: 4 }, 
      dragon: { height: 200, age: 350 } 
    };
    // GET /monsters/hydra
    app.get('/monsters/:name', (req, res, next) => {
      console.log(req.params); // { name: 'hydra' }
      res.send(monsters[req.params.name]);
    });

     

     


    < Setting Status Codes >

    To set the status code (200, 404... ) on responses using .status( ) method before they're sent.

     

    • The res object has a .status() method to allow us to set the status code, and other methods like .send() can be chained from it.

     

    ex)

    const monsterStoreInventory = { fenrirs: 4, banshees: 1, jerseyDevils: 4, krakens: 3 };
    app.get('/monsters-inventory/:name', (req, res, next) => {
      const monsterInventory = monsterStoreInventory[req.params.name];
      if (monsterInventory) {
        res.send(monsterInventory);
      } else {
        res.status(404).send('Monster not found');
      }
    });

    +. res.send() has by default sent a 200 OK status code.

     

     


    < Update Data Using Queries >

    To update Data using Queries!

    PUT is the HTTP method verb used for updating resources.
    Express uses .put( ) as its method for PUT requests.

     

    • Query strings appear at the end of the path in URLs, and they are indicated with a ? character. 
      For instance, in /monsters/1?name=chimera&age=1, the query string is name=chimera&age=1 and the path is /monsters/1/
    • Query strings do not count as part of the route path. Instead, the Express server parses them into a JavaScript object and attaches it to the request body as the value of req.query
      1) The key : value relationship is indicated by the =
      2) The key-value pairs are separated by &
      In the above example, the req.query object would be { name: chimera, age: 1 }

     

    ex)

    -> When a PUT /monsters/1?name=chimera&age=1 request arrives

    const monsters = { '1': { name: 'cerberus', age: '4'  } };
    // PUT /monsters/1?name=chimera&age=1
    app.put('/monsters/:id', (req, res, next) => {
      const monsterUpdates = req.query; // { name:chimera, age: 1 }
      monsters[req.params.id] = monsterUpdates; // monsters['1']
      res.send(monsters[req.params.id]);
    });

    : When updating, many servers will send back the updated resource after the updates are applied so that the client has the exact same version of the resource as the server and database.

     

     


    < Create Data >

    To create Data!

    POST is the HTTP method verb used for creating new resources.
    Express uses
    .post( ) as its method forPOSTrequests

     

    • Paths do not end with a route parameter.
      Because... For example, to create a new monster, a client would make a POST request to /monsters. The client does not know the id of the monster until it is created

     

    ex)

    app.post('/expressions', (req, res, next) => {
      const newExpression = createElement('expressions', req.query);
      if (newExpression) {
        expressions.push(newExpression);
        res.status(201).send(newExpression);
      } else {
        res.status(400).send();
      }
    })

    : The HTTP status code for a newly-created resource is 201 Created.

     

     


    < Delete Data >

    To delete Data!

    DELETE is the HTTP method verb used to delete resources.
    Express uses .delete( ) as its method for DELETE requests.

     

    ex)

    app.delete('/expressions/:id', (req, res, next) => {
      const expressionIndex = getIndexById(req.params.id, expressions);
      if (expressionIndex !== -1) {
        expressions.splice(expressionIndex, 1);
        res.status(204).send();
      } else {
        res.status(404).send();
      }
    });

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    'Node.js > Express' 카테고리의 다른 글

    Router Parameters  (0) 2021.11.18
    Middleware  (0) 2021.11.18

    댓글

Designed by Tistory.