실습은 TIL로 기록해야겠다ㅎㅎ
어떤 식으로 써야할지 고민이 많았는데 그냥 '쓰고 싶은 대로 써야 오래 쓴다'는 진리 같은 한문장을 보고 쓰고 싶은 대로 쓰기로 했다.
오늘은 http 모듈로 서버를 만들었다.
check 할 사항
- VSC에서 js코드 수정 후 꼭 ctrl+c로 껐다 켜야함
- return res.end(data) 꼭! 잊지 말아야한다. res.end 호출 앞에 return을 붙이지 않으면 함수가 종료되지 않는다.
더보기
const http = require('http')
const fs = require('fs').promises
const users = {} //데이터 저장용
const server = http.createServer(async (req, res) => {try {if (req.method === 'GET') {if(req.url === '/') {const data = await fs.readFile('./restFront.html')res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8'})return res.end(data)}
- createServer
더보기
const http = require('http')
const fs = require('fs').promises
const server = http.createServer(async (req, res) => { //async 사용try {throw new Error('에러 메세지 : 표시할 수 없는 화면입니다.')const data = await fs.readFile('./index.html')res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})res.end(data)} catch (err) {console.error(err)const data = await fs.readFile('./errormessage.html') // 이런 식으로 예외 처리 할 수도 있다 참고res.writeHead(500, {'Content-Type': 'text/html; charset=utf-8'})res.end(`<p>${err.message}</p>`)}})
//then으로 할 수도 있다(그러나 코드가 훨씬 지저분하다)// const server = http.createServer( (req, res) => {// const html = fs.readFile('./index.html')// html.then((data) => {// res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'})// res.end(data)// })// .catch(err => {// console.error(err)// })// })
server.listen(3000)server.on('listening', () => {console.log('포트 3000번에서 실행 중')})
- '/', '/blah~' : 라우터 주소
- JSON 많이 쓰는 2가지
더보기
JSON.parse() //JSON을 object로 변경
JSON.stringify() //object나 값을 JSON으로 변경
JSON
- "데이터이름":값
- 서버를 만들기 위해 짠 코드
더보기
const http = require('http')
const fs = require('fs').promises
const users = {} // 데이터 저장용
const server = http.createServer(async (req, res) => {try {if (req.method === 'GET') {if (req.url === '/') {const data = await fs.readFile('./restFront.html')res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })return res.end(data)} else if (req.url === '/about') {const data = await fs.readFile('./about.html')res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })return res.end(data)} else if (req.url === '/users') {res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' })return res.end(JSON.stringify(users))}try { // /restFront.css, restFront.jsconst data = await fs.readFile(`.${req.url}`)return res.end(data)} catch (err) {console.error(err)}} else if (req.method === 'POST') {if (req.url === '/user') {let body = ''
req.on('data', (data) => {body += data // body = body + data})
return req.on('end', () => {console.log('POST 본문(body):', body)const { name } = JSON.parse(body)const id = Date.now()users[id] = nameconsole.log(users)res.writeHead(201, {'Content-Type': 'text/plain; charset=utf-8'})res.end('ok')})}} else if (req.method === 'PUT') {if (req.url.startsWith('/user/')) { // /user/12390182309const key = req.url.split('/')[2]let body = ''req.on('data', (data) => {body += data;})return req.on('end', ()=> {console.log("PUT 본문:", body)users[key] = JSON.parse(body).nameres.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8'})res.end('ok')})}} else if (req.method === 'DELETE') {if(req.url.startsWith('/user/')) {//req.url '/user/1293801932'.split('/')const key = req.url.split('/')[2]delete users[key]res.writeHead(200, { 'Content-Type' : 'text/plain; charset=utf-8' })return res.end('ok')}}} catch(err) {console.error(err)res.writeHead(500, {'Content-Type': 'text/plain; charset=utf-8'})res.end(err.message)}})
server.listen(3000)
server.on('listening', ()=> {console.log('3000번 포트에서 서버 실행중')})server.on('error', (err)=> {console.error(err)})
사실 이렇게 잘 안하고 내일 다른 방법(express)을 배울 예정이다. 어떻게 작동 되는지는 대충 알 것 같다. 로직을 이해한다는 게 이런 건가? 정말 흥미로운 세계다.
- GET / POST / PUT / PATCH / DELETE => REST API SERVER
'공부 > [TIL] Digital Twin Bootcamp' 카테고리의 다른 글
TIL_211221_Frontend (0) | 2021.12.21 |
---|---|
TIL_211220_Frontend (0) | 2021.12.20 |
TIL_211217_Frontend (0) | 2021.12.17 |
TIL_201216_Frontend (0) | 2021.12.16 |
TIL_211215_BACKEND (0) | 2021.12.15 |