728x90
반응형

오늘 배운 것

알고리즘 풀이

스파르타코딩클럽 입문 복습

스파르타코딩클럽 심화 시작

오늘 느낀 점

vs코드를 쓰다가 서버를 실행했는데 실행이 안되길래

몇십분동안 왜 안될까? 하면서 문제를 찾아다녔는데

app.js 파일이 이상한 폴더안에 들어간 상태여서 실행이 안됬다ㅠㅠ

그래서 강사님이 쓰는 것처럼 명확하게 보이는 라이브러리를 설치했더니 보기 깔끔해졌다.

 

입문 복습끝내고 심화시작하니 초반부분이긴 하지만

이해를 하면서 따라가고 있다. 이제 조금은 마음이 편-안!

728x90
반응형

'일기 > TIL' 카테고리의 다른 글

TIL: Today I Learned 29일차 [Docker 설치오류]  (0) 2022.12.22
TIL: Today I Learned 28일차  (0) 2022.12.21
TIL: Today I Learned 26일차  (0) 2022.12.19
TIL: Today I Learned 25일차  (0) 2022.12.16
TIL: Today I Learned 23일차  (0) 2022.12.14
728x90
반응형

Validation이란 무엇인가?

Validation은 말 그대로 어떤것을 검증한다고 보면 됩니다.

 

검증을 위한 라이브러리 추천 joi (https://joi.dev/api/)

//예제코드
const Joi = require('joi');

const schema = Joi.object({
    username: Joi.string()
        .alphanum()
        .min(3)
        .max(30)
        .required(),

    password: Joi.string()
        .pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),

    repeat_password: Joi.ref('password'),

    access_token: [
        Joi.string(),
        Joi.number()
    ],

    birth_year: Joi.number()
        .integer()
        .min(1900)
        .max(2013),

    email: Joi.string()
        .email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })
})
    .with('username', 'birth_year')
    .xor('password', 'access_token')
    .with('password', 'repeat_password');


schema.validate({ username: 'abc', birth_year: 1994 });
// -> { value: { username: 'abc', birth_year: 1994 } }

schema.validate({});
// -> { value: {}, error: '"username" is required' }

// Also -

try {
    const value = await schema.validateAsync({ username: 'abc', birth_year: 1994 });
}
catch (err) { }
728x90
반응형
728x90
반응형

function solution(numbers) {
    var answer = [];
    for(i=0; i<numbers.length; i++){
        answer[i] = numbers[i]*2
    }
    return answer;
}
728x90
반응형
728x90
반응형
const express = require('express');
const app = express();
const port = 3000p
const goodsRouter = require('./routes/goods.js');

app.use(express.json()); //바디파서를 전역미들웨어로 사용할꺼다!

app.post("/", (req,res) => {
	console.log(req.body); // {"key":"value"}
    const obj = {
    	"이름": "표정훈",
        "나이": "33"
    }
	res.json(obj);
});

app.get("/", (req,res) => {
	console.log(req.query); //key와 value 값을 받겠다 [ ?Key=Value ]
	res.json();
});

app.get("/:id", (req,res) => {
	console.log(req.params);  // 기본주소 / 뒤에 붙은걸 받겠다!
    res.send(":id URI 정상반환");
})
728x90
반응형
728x90
반응형

오늘 배운 것

알고리즘 풀이

스파르타코딩클럽 입문 복습

Node.js 유튜브 공부

https://pyoja.tistory.com/110

오늘 느낀 점

스파르타 강의는 어려운 부분이 있어서

유튜브에 있는 쉽게 알려주는 강의를 찾아서 개념을 익혔다.

다 듣고나니 이전엔 어렵게 느껴지던 강의가

조금은 더 쉽게 이해가 되서 뿌듯하다.

 

그외 헷갈렸던 정의들도 따로 적어가며 복습하고 있다.

 

<화살표함수>
function() {}
()=> {}

function(){} 과 () =>{}
function 대신 =>

<promise == async>
function 함수이름(){  return Promise.reslove('값');  }
async function 함수이름(){ return '값';) 은 동일하다!

<자바스크립트 비동기(논블럭킹) 함수>
동기로 쓰고 싶다면 promise = async 를 쓰면 됨!
(예약걸어서 기다리게 하고 싶다면!)

await은 기다려!!
나 실행되고 너 되야대!! (안쓰면 다른거 먼저됨)

객체리터럴 = 객체를 생성하기 위한 표기법
프로퍼티 = 객체의 상태를 나타내는 값(key와 value로 구성)
메서드 = 객체의 프로퍼티 값이 함수로 구성될 경우 메서드

728x90
반응형

'일기 > TIL' 카테고리의 다른 글

TIL: Today I Learned 28일차  (0) 2022.12.21
TIL: Today I Learned 27일차  (0) 2022.12.20
TIL: Today I Learned 25일차  (0) 2022.12.16
TIL: Today I Learned 23일차  (0) 2022.12.14
TIL: Today I Learned 22일차  (0) 2022.12.13
728x90
반응형

DB없이 게시판 만들기 [express, ejs]

 

deploy : https://port-0-crud-sqlite-jocoding-53px25lbuimiei.gksl2.cloudtype.app/

깃허브저장소 : https://github.com/pyoja/crud_sqlite_jocoding

 

index.js

var express = require('express');
var app = express();

let comments = [];

// req.body 오는 값을 읽기 위해 적용
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

// <%= %> 또는 <% %> 같이 html에서 js를 쓰기위한 ejs 라이브러리
app.set('view engine', 'ejs');

// index page
app.get('/', function(req, res) {
  res.render('index', {comments: comments});
});

app.post('/create', function(req, res) {
    console.log(req.body)
    const {content} = req.body //form태그에 있는 name="content"
    comments.push(content)
    console.log(comments)
    res.redirect('/')
});

app.listen(3000);
console.log('Server is listening on port 3000');

index.ejs

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>내 페이지</title>
</head>
<body>
    <h1>댓글 목록</h1>
    <ul>
    <% for (comment of comments) { %>
         <li><%= comment %></li>
    <% } %>
    </ul>
    <hr>
    <form action="/create" method="post">
        <input type="text" id="lname" name="content"><br><br>
        <input type="submit" value="Submit">
      </form>
</body>
</html>

sqlite를 이용한 DB활용

https://sequelize.org/ 를 이용하여 SQL문법이 아닌 JS 문법으로 DB이용

index.ejs

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>내 페이지</title>
</head>
<body>
    <h1>댓글 목록</h1>
    <ul>
    <% for (comment of comments) { %>
         <li><%= comment.id %> <%= comment.content %></li>
         <form action="/update/<%= comment.id %>" method="post">
            <input type="text" name="content">
            <input type="submit" value="수정하기">
          </form>
          <form action="/delete/<%= comment.id %>" method="post">
             <input type="submit" value="삭제하기">
           </form>
    <% } %>
    </ul>
    <hr>
    <form action="/create" method="post">
        <input type="text" id="lname" name="content"><br><br>
        <input type="submit" value="Submit">
      </form>
</body>
</html>

index.js

var express = require('express');
var app = express();

const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: 'database.sqlite'
  });

const Commnets = sequelize.define('Commnets', {
  content: {
    type: DataTypes.STRING,
    allowNull: false
  },

}, {
  // Other model options go here
});

(async() => {
await Commnets.sync();
})();

// req.body 오는 값을 읽기 위해 적용
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

// <%= %> 또는 <% %> 같이 html에서 js를 쓰기위한 ejs 라이브러리
app.set('view engine', 'ejs');

// index page
app.get('/', async function(req, res) {
    const comments = await Commnets.findAll();
    res.render('index', { comments: comments });
});

app.post('/create', async function(req, res) {
    console.log(req.body)
    const {content} = req.body //form태그에 있는 name="content"
    await Commnets.create({ content : content });
    res.redirect('/')
});

app.post('/update/:id', async function(req, res) {
    const {content} = req.body
    const {id} = req.params
    await Commnets.update({ content: content }, {
    where: {
      id: id
    }
  });

    res.redirect('/')
});

app.post('/delete/:id', async function(req, res) {
    const {id} = req.params
    await Commnets.destroy({
    where: {
      id: id
    }
  });
    res.redirect('/')
});

app.listen(3000);
console.log('Server is listening on port 3000');
728x90
반응형
728x90
반응형

function solution(num_list) {
    var answer = [];
    for(i=0; i<num_list.length; i++){
        answer[i] = num_list[num_list.length-1-i]
    }
    return answer;
}
728x90
반응형
728x90
반응형

https://www.youtube.com/watch?v=SGGebq48h3Y 참고 조코딩 영상

 

배포(Deploy)의 개념

 

무료 배포 사이트 [클라우드 타입] https://cloudtype.io/

 

클라우드 타입 사용방법

 

깃허브로 가입&로그인 후

깃 허브 저장소는 미리 만들어줘야하고,

애플리케이션은 노드의 버전을 확인하는데

터미널에서 node -v 를 입력하면 버전이 확인 됨

 

배포하기를 누른후에 설정에서

아래와 같이 설정해야함

 

Start Command = node index.js

Install Command = npm ci --production  [패키지 락에 있는 정보를 기반으로 설치]

 

 

완료되면 도메인으로 접속가능

.

완성

https://port-0-node-animal-sound-883524lbrr4u1h.gksl2.cloudtype.app/

https://port-0-node-animal-sound-883524lbrr4u1h.gksl2.cloudtype.app/sound/cat

 

https://port-0-node-animal-sound-883524lbrr4u1h.gksl2.cloudtype.app/

 

port-0-node-animal-sound-883524lbrr4u1h.gksl2.cloudtype.app

 

728x90
반응형

+ Recent posts