웹프로그래밍
-
쿠키와 세션 구현하기웹프로그래밍/node.js 2019. 8. 9. 15:10
쿠키 설정하기 const http = require('http'); const parseCookies = (cookie = '') => cookie .split(';') .map(v => v.split('=')) .reduce((acc, [k, v]) => { acc[k.trim()] = decodeURIComponent(v); return acc; }, {}); const server = http.createServer((req, res) => { //req.headers.cookie const cookies = parseCookies(req.headers.cookie); console.log(req.url, cookies); res.writeHead(200, { 'Set-Cookie': 'mycook..
-
http 모듈웹프로그래밍/node.js 2019. 8. 8. 16:49
node는 서버가 아니고 런타임이다. http모듈이 서버 역할을 한다. const http = require('http'); // http모듈이 서버 역할을 한다. // node는 서버가 아니고 런타임 //이벤트 명은 써줄 필요가 없다. http.createServer((req, res) => { console.log('서버 실행'); res.write('Hello Node!'); res.write('Hello JS!'); res.write('Hello JS!'); res.end('Hello Server!'); }).listen(8080, () => { console.log('8080번 포트에서 서버 대기중입니다.'); }); //http 기본포트(80) //https (443) //기본 포트는 생략가능..
-
예외처리웹프로그래밍/node.js 2019. 8. 8. 13:32
노드는 싱글쓰레드이기 때문에 하나가 죽으면 전체 서버가 죽기 때문에 예외처리가 필수이다. setInterval(()=> { console.log('시작'); throw new Error('서버를 고장내주마'); },1000); setInterval로 1초마다 콜백이 실행되게 해주는데 error가 발생하니까 바로 서버가 죽어버렸다. try/catch문을 활용 setInterval(()=> { console.log('시작'); try { throw new Error('서버를 고장내주마'); } catch (error) { console.error(error); } },1000); 서버가 죽지않고 계속 1초마다 실행된다. 하지만 에러가 나면 내보내는게 아니고 처리를 해야하기 때문에 try/catch를 권장하지..
-
events모듈웹프로그래밍/node.js 2019. 8. 8. 13:11
미리 이벤트리스너를 만들어두고, (이벤트 리스너를 특정 이벤트가 발생했을 때 어떤 동작을 할지 정의하는 부분) 예시) 사람들이 서버에 방문(이벤트)하면 HTML 파일을 준다. const EventEmitter = require('events'); const myEvent = new EventEmitter(); myEvent.addListener('방문', () => { console.log('방문해주셔서 감사합니다.'); }); myEvent.on('종료', () => { console.log('안녕히가세요.'); }); myEvent.on('종료', () => { console.log('제발 좀 가세요'); }); // on과 addEventListener는 같은 기능을 하는 별명이다. myEvent...
-
util 모듈 && fs 모듈웹프로그래밍/node.js 2019. 8. 7. 23:05
util 모듈 util.deprecate는 지원이 조만간 중단될 메서드임을 알려줄 때 사용한다. const util = require('util'); const crypto = require('crypto'); //deprecated는 지원이 조만간 중단될 메서드임을 알려줄 때 사용 const dontuseme = util.deprecate((x,y)=>{ console.log(x+y); }); dontuseme(1, 2); 함수를 사용하면 콘솔에 값은 나오지만 경고도 함께 출력 된다. util.promisify로 promise를 지원하지 않는 (err, data) => {} 꼴의 콜백 또한 프로미스로 만들 수 있다. const randomBytesPromise = util.promisify(crypto..
-
path모듈 && url모듈 && crypto모듈웹프로그래밍/node.js 2019. 8. 7. 19:13
path 모듈 path.sep windows(\\) path.delimiter //환경변수 구분자 windows(;) const path = require('path'); console.log(path.dirname(__filename)); //경로 //C:\Users\hjoo_\Documents\nodejs-start\lecture console.log(path.extname(__filename)); //확장자 //.js console.log(path.basename(__filename)); //파일명 //path.js console.log(path.parse(__filename)); //분해를 해준다 // { root: 'C:\\', // dir: 'C:\\Users\\hjoo_\\Documents\..
-
데이터베이스웹프로그래밍/node.js 2019. 6. 4. 14:26
데이터 베이스 SQL - 테이블 형식의 데이터베이스 - MySQL, PostgreSQL, Aurora, Sqlite NoSQL - 테이블 형식이 아니라 도큐먼트 형식의 데이터베이스 (json 형식) - 데이터베이스의 형식을 쉽게 변경할 수 있다. - MongoDB, DynamoDB In Momory DB - 메모리 안에 데이터 베이스를 저장해 놓는 형식 (서비스의 성능 향상을 위해 사용함) - Redis, Memcashed SQL 쿼리 기초 insert users ('name') values ('alice'); select * from users; update users set name = 'bek' where id = 1; delete from users where id = 1; ORM 데이터베이스를 ..
-
사용자 수정 API 성공, 실패시웹프로그래밍/node.js 2019. 6. 3. 19:03
PUT /users/:id 성공 변경된 name을 응답한다 실패 정수가 아닌 id일 경우 400 응답 name이 없을 경우 400 응답 없는 유저일 경우 404 응답 이름이 중복일 경우 409 응답 index.spec.js 코드 추가 describe('PUT /users/:id', ()=> { describe('성공시', ()=> { it('변경된 name을 응답한다', (done)=> { // 비동기면 done을 써줘야함 const name = 'chally'; request(app) .put('/users/3') .send({name}) .end((err, res)=> { res.body.should.have.property('name', name); done(); }); }); }); describ..