W5D2 Package, npm, Express.js, and Request & Response

Jin Bae·2022년 12월 13일
0

스파르타코딩클럽

목록 보기
20/35

Package Manager

A package manager is a tool to easily handle packages. In Node.js, the top package managers are npm and yarn.

npm is similar to pip in Python.

yarn is a package manager published by Facebook. It has convenient functions to fill in disadvantages of npm and can manage packages faster.

An error can occur if both npm and yarn are used in a project. If two different versions of a package are installed, a conflict can occur.

Package.json is a file that manages the version of the installed packages. Other metadata, such as project name, author, or license information, can be recorded. Both npm and yarn referens Package.json.
It installs files according to my environment the node_modules folder and SHOULD NOT be shared.

Package-lock.json records the package versions and relationships of packages in node_modules. When a package is installed, edited, or deleted using npm, the relationship is recorded in package-lock.json. This can be used to record exactly what package version is being used in a project.

npm

npm init is used in the terminal to create package.json. Used for a new project or package.

npm install packageName installs a package. i can be used instead of install. Multiple packages can be installed using spaces.

npm install -D moduleName installs modules only needed for the development stage.

Express.js

Express.js is a web framework to quickly and convieniently create a server.
Can be installed with npm i express.

This module provides an expansion of the http module. The default methods from the http module can be used, as well the additional methods and properties of the Express module. The Express methods are more convenient and the http module is used less.

Routing and router

Routing is a way to respond to the client's requests (method, address, etc.).
Router helps to easily execute a client's request and is one of the basic functions of Express.js.

A router is usually made as the following:

router.METHOD(PATH, HANDLER);

Module

Modules are code separated into files. It can call another module and use it.

  • They are used to manage code structurally
  • Allows codes to be modularized, meaning they can be reused
  • Only the module's interface is shown. It can be used to hide information.
  • Allows to manage dependencies

CommonJS

A convention that establishes the module ecosystem. Node.js uses CommonJS by default. Imports using the require() function and exports using module.exports.

// Import 'express' package
const express = require('express')

// Declare function as anonymous exported function object
exports.add = function add(a, b) {
    return a+b
}

// Export function add() (Not needed when function is exported as an object)
module.exports = add;

// Export function add as an object:
module.exports = {add: add};

ECMA Script Module (ESM)

A system started to provide a comprehensive interface in Javascript. As opposed to CommonJS

// Import 'express' package as name express
import express from 'express'

// Declare function as anonymous exported function object
export function add(a, b) {
    return a+b
}

// Export function add() (Not needed when function is exported as an object)
export default add;

// Export function add as an object:
export const add = add;

Request and Response

Request: an object that contains the information or message sent from the client to the server
Response: an object that sends a message from the server to the client

Req objects

  • req.app : req 객체를 통해 app 객체에 접근할 수 있습니다.
  • req.ip: 요청한 Client의 ip 주소가 담겨 있습니다.
  • req.body: Request를 호출할 때 body로 전달된 정보가 담긴 객체입니다.
    • express.json() Middleware를 이용하여야 해당 객체를 사용할 수 있습니다.
    • Used for the POST and PUT methods
  • req.params: 라우터 매개 변수에 대한 정보가 담긴 객체입니다.
  • req.query: Request를 호출할 때 쿼리 스트링으로 전달된 정보가 담긴 객체입니다.
    - Used for the GET method
  • req.cookies: Request를 호출할 때 Cookie 정보가 담긴 객체입니다.
    • cookie-parser Middleware를 이용하여야 해당 객체를 사용할 수 있습니다.
  • req.get(Header): 헤더에 저장된 값을 가져오고 싶을 때 사용합니다.

Res objects

  • res.app : res 객체를 통해 app 객체에 접근할 수 있습니다.
  • res.status(코드) : Response에 HTTP 상태 코드를 지정합니다. → Http 상태 코드에 대해 자세히 알고싶다면 여기를 클릭해주세요!
  • res.send(데이터) : 데이터를 포함하여 Response를 전달합니다.
  • res.json(JSON) : JSON 형식으로 Response를 전달합니다.
  • res.end() : 데이터 없이 Response를 전달합니다.
  • res.direct(주소) : 리다이렉트할 주소와 함께 Response를 전달합니다.
  • res.cookie(Key, Value, Option) : 쿠키를 설정할 때 사용합니다.
  • res.clearCookie(Key, Value, Option) : 쿠키를 제거할 때 사용합니다.

API

A medium (매개체) that connects applications together.
Provides a URL and interface that executes a desired function from the web application (front end). The API must get data to save it to the database or provide data from the saved database to the web application (front end).

REST API

REST (Representational State Transfer) is a software architecturefor the hypermedia system. This is an API that follows the REST architecture.
Simply put, one must understand what the API is doing by seeing the URL, Headers, Method, etc.

1. 자원 (Resource) - URL

Everything a software manages can be described as a resource.

2. 행위 - HTTP Method

Refers to CRUD

  • Create: POST
  • Read: GET
  • Update: PUT, PATCH
  • Delete: DELETE

0개의 댓글