ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 1
    카테고리 없음 2022. 11. 14. 11:39

    cmd

    cd Desktop
    mkdir bolier-plate
    cd bolier-plate


    bolier-plate>npm init

    입력 후 엔터로 기본설정해준다
    C:\Users\user\Desktop\bolier-plate>code .  

    vscode열기

    index.js파일 생성후

    nodejs의 프레임워크인 expressjs를 설치해준다

    vscode 터미널에서 npm install express --save (--save package.json에 표시)

    https://expressjs.com/ko/starter/hello-world.html

     

    Express "Hello World" 예제

    Hello world 예제 기본적으로 이 앱은 여러분이 작성할 수 있는 가장 간단한 Express 앱일 것입니다. 이 앱은 하나의 파일로 된 앱이며 Express 생성기를 통해 얻게 되는 앱과는 같지 않습니다. (이 예제

    expressjs.com

    index.js파일에 코드 추가

    //express모듈을 가져온다
    const express = require("express");
    //express app을 만든다
    const app = express();
    //포트번호
    const port = 5000;
    //루트 디렉토리에 오면 hello world!출력되게 해준다
    app.get("/", (req, res) => {
      res.send("Hello World!");
    });
    //5000번 포트에서 앱을 실행
    app.listen(port, () => {
      console.log(`Example app listening on port ${port}`);
    });

    package.json에서 추가

    "scripts": {
        "start": "node index.js",

    터미널에서 npm run start하면 node앱을 실행하게 된다 시작점 index.js

    npm run start 입력 후

    http://localhost:5000/ 에 접속해보면 Hello world!가 출력되는 것을 확인할 수 있다

     

    기본강의3

    MongoDB 연결하기

     MongoDB 페이지에서 로그인 후 cluster만든다

    pjoject생성으로 들어가서 새로운 프로젝트 생성을 누르고

    이름을 입력한 후 create cluster 페이지로 넘어간다

    aws 클릭 후 가장 가까운 곳 선택

    M0 Sandbox(free) 선택 후 cluster name을 설정하고 create cluster 

     

    유저생성

    create a MongoDB user

    원하는 username과 password를 작성한다

    database에서 connect를 누른 후 설정해준다 current ip 추가 후

    Choose a connection method -> connect your application

    나오는 코드를 연결할 application 파일에 입력해준다

     

    mongoose 설치

    npm install mongoose --save

    설치 후 package.json 파일에서 dependencies에 자동으로 mogoose추가된 것을 확인할 수 있다

     

    mongoDB연결

    const mongoose = require("mongoose");
    mongoose.connect("복사했던 application코드 설정했던password까지 입력 후 붙여넣기", {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
      //연결확인
      .then(() => console.log("MongoDB connected..."))
      //오류출력
      .catch((err) => console.log(err));

    입력 후 npm run start 실행시 mongoDB 연결이 나오게 된다

     

    MongoDB Model & Schema

    회원가입시 유저의 이름이나 나이 사는 곳 등 입력할 경우 정보가 유저 데이터베이스에 들어가게 되는데

    유저와 관련된 데이터를 보관하기 위해 usermodel, userschema를 만든다

    model은 schema를 감싸주는 역할을 한다 schema는 상품에 관련된 글을 작성할 경우 작성자나 포스트의 이름의 타입 등을  지정한다

    const mongoose = require("mongoose"); 
    
    const userSchema = mongoose.Schema({
      //user 이름
      name: {
        type: String,
        maxlength: 50,
      },
      //user email
      email: {
        type: String,
        trim: true, // space 제거
        unique: 1, // 같은 이메일을 쓰지 못하게 unique 추가
      },
      //user 비밀번호
      password: {
        type: String,
        minlength: 5,
      },
      //user lastname
      lastname: {
        type: String,
        maxlength: 50,
      },
      // 유저의 역할(관리자, 일반유저 등)
      role: {
        type: Number, // 1: 관리자, 0: 일반유저 등의 형식으로 관리
        default: 0,
      },
      // user 이미지타입 token을 이용해 유효성 관리
      image: String,
      token: {
        type: String,
      },
      // 토큰의 유효기간
      tokenExp: {
        type: Number,
      },
    });
    //mongoose.model을 호출 할 때 Schema 등록
    const User = mongoose.model("User", userSchema); 
    //다른 파일에서도 쓸 수 있게 export해준다
    module.exports = { User };

     git 설치 및 ssh를 이용해 github와 연결

    git 설치확인

    git --version

    git version이 안 나올 경우 https://git-scm.com/ 사이트에서 다운로드한다

    설치확인 후 사용 application 터미널에서 깃 저장소를 만들기 위해  입력

    git init

     

    git 상태확인

    git status

    working directory에 있는 파일들을 staging area에 추가

    node_modules부분은 저장소에 올리지 않아도 된다

    git add . 입력 전에 .gitignore파일에 node_modules를 추가해준다

    git add .을 이미 입력했을 경우 git rm --cached node_modules -r 입력해 제거해준다

    //. 모든 파일을 추가한다
    git add .

    git repository에 업로드(local)

    git commit -m "메세지입력"

    다시 git status로 확인하면 아무것도 안 뜨는 것을 확인할 수 있다(저장소에 올라갔기 때문에)

     

    github업로드

    local에 올린 파일들을 github에 업로드한다 github은 클라우드 서비스 git은 tool

    github로그인 후 New버튼 클릭 후에 repository생성한다

     

    ssh사용

    설치확인

     

    컴퓨터와 git이 안전하게 통신하게 하기 위해 ssh설정

    ssh설치

    페이지에 들어가서 사용환경에 따라 설치한다 enter로 설치

    https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

    설치 후 background 실행시 

    eval "$(ssh-agent -s)"

    ssh private key ssh agent에 추가

    ssh-add ~/.ssh/id_ed25519

    github계정에 ssh추가

    https://docs.github.com/en/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account

     

    Adding a new SSH key to your GitHub account - GitHub Docs

    About addition of SSH keys to your account You can access and write data in repositories on GitHub.com using SSH (Secure Shell Protocol). When you connect via SSH, you authenticate using a private key file on your local machine. For more information, see "

    docs.github.com

    링크에 나온 코드 git bash에 입력하면 클립보드에 저장된다

    github settings에서 SSH AND GPG keys클릭 후 New ssh key눌러서 클립보드에 복사된 ssh key를 저장해준다

    github과 연결하기 위해 순서대로 입력

    git remote add origin git@github.com:깃헙사용자이름/깃헙저장소이름.git
    git branch -M main
    git push -u origin main

    This key is not known by any other names
    Are you sure you want to continue connecting (yes/no/[fingerprint])? 에서 yes입력

    깃헙에서 업로드된 파일 확인한다

     

    회원가입기능

    브라우저에서 유저에게 받은 정보들을 서버로 보내기 위해 body-parser사용(client에서 넘어오는 정보를 서버에서 분석해 가져오게 하는 기능) bodyparser사용해 req.body데이터를 유저

    body-parser다운 

    터미널에 입력해준다

    npm install body-parser --save

    post man 다운

    https://www.postman.com/downloads/

    register route만들기

    index.js에 추가한다

    const bodyParser = require("body-parser");
    const { User } = require("./model/User");
    
    //application/x-www-form-urlencoded 타입으로 된 것을 분석해서 가져올 수 있게 하는 코드
    app.use(bodyParser.urlencoded({ extended: true }));
    //application/json 타입으로 된 것을 분석해서 가져올 수 있게 하는 코드
    app.use(bodyParser.json());

    register route

    //register route만들기
    app.post("/register", (req, res) => {
      //회원가입할때 필요한 정보들을 client에서 가져오면 그것들을
      //데이터베이스에 넣어준다
      //req.body로 client정보를 받아준다
      //저장할때 error가 있으면 client에 err전달(json형식) 
      const user = new User(req.body);
      user.save((err, userInfo) => {
        if (err) return res.json({ success: false, err });
        return res.status(200)({
          success: true,
        });
      });
    });

    postman 로그인 후 post형식 body, json설정 후 내용후가(api테스트)

    {
        "name": "jhon123",
        "email": "jhon123@naver.com",
        "password":"1234567"
    }

     send버튼 누른 후 response에 sucess:true가 뜨는 것을 확인한다

Designed by Tistory.