-
항해 99 5기 TIL_16항해 99 2022. 1. 26. 02:32
▶ Today I Learned
<CS 스터디>
[전기이론]
전류는 current (기호 I), 전압은 voltage (기호는 V), 저항은 resistance (기호는 R)
I = V/R
도체: 전도도가 높아서 전기가 흐르기 쉬운 재료
부도체: 전기나 열을 전달하기 어려운 재료, 절연체 라고도 함, 온도가 높아지면 원자에서 전자들이 분리되어 이동할 가능성이 높아짐
-> 전기저항이 감소함
반도체: 도체와 부도체의 중간 정도로 전기가 흐르는 재료. 부도체와 마찬가지로 온도가 높아지면 전기 저항이 감소함
<홈페이지 구현>
[npm init]
Node Package Manager의 약자 npm, node.js에서 사용하는 모듈들은 패키지로 만들어 관리하고 배포하는 역할
npm init을 하면 package.json를 만듬. package.json이란 패키지에 관한 정보와 의존중인 버전의 정보를 담고 있음
[app.listen]
const app = express() 로 설정했다.
여기서 app.listen이란 특정호스트와 포트를 연결시키고 확인해보는 기능이다.
문법은 다음과 같다.
app.listen([port[, host[, backlog]]][, callback])
나의 경우는 포트에 3000번을 쓰고 뒤에는 콘솔에 찍는 메시지를 입력하였다.
[미들웨어]
웹서버에서 받는 요청에 대해 공통적인 처리를 해줌
ex) 모든 요청에 로그 남기기, 특정 API 특정 사용자만 접근가능하게 하기
[express.js]
express.static으로 기본 루트 지정하여 static파일 가져올 수 있음
express.static(root, [options])
공식문서에 따르면 html의 디폴트 값은 index.html이라고 함
그러나 폴더를 만들고 index.html 생성 후 기본루트로 지정해도 메인페이지로 이동이 되지 않는다.
=> 알고 보니 해당 코드가
app.get('/', (req, res) => { res.send('Hello World!'); });
이것 보다 늦게 나와서 그랬던 것! 문제 해결 ;)
앞으로는 순서도 한 번 더 고려하자~!
[Router 미들웨어]
const helloRouter = require("./routes/hello"); app.use("/api", [helloRouter]);
예를 들어 이렇게 작성하면 localhost 뒤에 /api로 시작되는 주소는 routes/hello 에 있는 Router 미들웨어를 통해
처리된다. 즉, hello에서 가령 경로를 /posting 으로 지정한다면 이는 실제로
http://localhost:포트번호/api/posting과 같다는 뜻임
[req.params vs req.body]
url로 값을 입력 받는 것은 req.params로,
코드 내 데이터(ajax콜 post 메서드)로 받는 것은 req.body로
[bodyparser and urlencoded]
게시글을 작성하여 제목, 작성자, 내용을 ajax콜로 넘겨 express router 파일로 받아 DB에 저장하려 했다.
그러나 잘 되지 않았다..!
function new_posting () { let title = $('#title').val(); let name = $('#name').val(); let text = $('#text').val(); $.ajax({ type: "POST", url: "/api/new_posting", data: { title_give: title, name_give: name, text_give: text, }, error: function (xhr, status, error) { // 에러 시 코드 }, success: function (response) { alert('test'); }, });
router.post("/new_posting", async (req, res) => { // db에 저장 // body는 payload와 같은 것, 전송하는 데이터, get을 제외한 method들에서 보통 사용함 // const goodsId = req.body.goodsId; 이 코드를 아래와 같이 바꿀 수 있음 -> destructure, 비할당구조화 const {title_give,name_give,text_give} = req.body; console.log(title_give,name_give,text_give); const createPostings = await new_posting.create({ title_give, name_give, text_give }) // create을 하면 생성과 동시에 insert 해주는 것과 같은 역할 console.log("4") res.json({ postings: createPostings }); });
테스트를 위해 콘솔을 중간중간 찍어가며 확인했지만 원인을 알 수 없었다.
데이터가 중간에
console.log(title_give,name_give,text_give);
를 찍었을 때 값이 undefined가 나왔다.
변수는 선언되어있다는 건데 값이 넘어오질 않았다
결국 알아낸 것은 app.js에 다음의 코드를 추가해야 한다는 것이다.
app.use(express.json()); // express가 json형태로 된 body를 가져와서 사용할 수 있게 해주는 미들웨어 // json 해석은 따로 모듈 필요 app.use(express.urlencoded()); // json 형식의 데이터를 해석하기 위해서는 bodyparser(urlencoded)가 필요하다. // 다만 최신 버전의 경우 모듈 내 body parser가 내장되어 있어서 express.urlencoded 로 작성해도 문제가 없다.
json 코드는 이미 있었지만 아래에 urlencoded를 추가해야 했다.
url과 관련이 있어보이지 않아 왜 하필 urlencoded인지는 모르겠지만 json형태로 된 response 값을 해석해줄 모듈을 따로 이용하여야
한다는 사실을 알게 되었다.
▶ 느낀 점
urlencoded 부분에서 사실 혼자서 해결하기 힘들었던 차에 먼저 끝낸 팀원 분께서 혹시 안되는 것이 있는지 물어봐주셨다. 그렇게 같이 원인분석을 하기 시작했고 중간에 다른 팀원 분들이 또 합류해주셔서 결국에 문제를 해결할 수 있었다. 이게 바로 협업이자 집단 지성의 힘이구나 라는 생각이 들었다. 혼자했다면 반나절이 걸릴 수도 있었을 것 같은데.. 같이 하니 그래도 1시간만에 찾게되었다..!
사람은 서로 가진 생각과 관점이 달라서 내가 보지 못한 것을 다른 이가 봐줄 수도 있다.
그래서 서로 돕다 보면 끝에는 모두의 시야가 넓어지고 문제해결능력도 향상되는 것 같다.
앞으로도 협업을 많이 해보아야 겠다.
도움을 받기도 하고 도움을 주기도 하며 :)
▶ 공부 시 참고 링크들
https://m.blog.naver.com/ckdgh930314/221801015725
https://www.geeksforgeeks.org/express-js-app-listen-function/
https://expressjs.com/en/4x/api.html#express.static
https://www.digitalocean.com/community/tutorials/nodejs-serving-static-files-in-express
https://bulma.io/documentation/overview/start/
https://blog.naver.com/PostView.nhn?blogId=dlaxodud2388&logNo=222111402593
https://velog.io/@yejinh/express-%EB%AF%B8%EB%93%A4%EC%9B%A8%EC%96%B4-bodyParser-%EB%AA%A8%EB%93%88
https://expressjs.com/ko/api.html#express.urlencoded
https://mongoosejs.com/docs/guide.html#definition
'항해 99' 카테고리의 다른 글
항해 99 5기 TIL_18 (0) 2022.01.28 항해 99 5기 TIL_17 (0) 2022.01.27 항해 99 5기 TIL_15 (0) 2022.01.25 항해 99 5기 WIL_2 (0) 2022.01.23 항해 99 5기 TIL_14 (0) 2022.01.23