fetch 함수로 받아온 데이터를 js에서 쓸 수 있도록 가공할 수 있게 만들어주는 method. 서버로부터 받은 response body 부분에 있는 데이터를 읽고, parsing 처리를 해준다.
fetch(url).then(res => res.json())
Node.js에서 본 함수 이용 시, 꼭 앞에 window를 써줘야지 해당 method를 쓸 수 있다. 기본적으로 브라우저에 내장된 method이기 때문에 전역객체인 window를 붙여줘야 하는것.
document.querySelector(class,id).value 처리를 통해 content에 접근 가능.
input 과 같은 form 요소의 값을 가져오고 싶으면 .value 를 쓰고, 그 외 div 나 span 등의 요소 안에 있는 텍스트를 읽고 싶으면 .textContent 등의 메소드를 쓴다.
참조
해커가 삽입한 스크립트 내 tag 기능을 무효화하기 위해서
하기와 같이 template으로 작성함. replace part는 꺽쇠(<,>) 발견 시 뒤에 있는 문자열로 변화시키는 기능을 위해 쓰임.
renderMessage: ({ username, text, date, roomname }) => {
const tmpl = `<div class="chat">
<div class="username">${username
.replace(/</g, '<')
.replace(/>/g, '>')}</div>
<div>${text
.replace(/</g, '<')
.replace(/>/g, '>')}</div>
<div>${date}</div>
<div>${roomname
.replace(/</g, '<')
.replace(/>/g, '>')}</div>
</div>`;
document.querySelector('#chats').innerHTML =
tmpl + document.querySelector('#chats').innerHTML;
},
input tag 안에 있는 내용을 submit 하는 기능작동을 중지시키는 역할이 있음. 하지만 하기 코드에서는 submit 시, 화면이 깜박거리는 현상을 없애기 위해 사용함.
submitMyPost.addEventListener('click', function(data){
data.preventDefault(); // submit 누르면 화면이 깜박거리는 것을 방지.
app.clearMessages();
console.log("a");
app.send({ // 한번만 쓸 변수나 상수는 상단에 선언하지 말자.
username: document.querySelector('.inputUser').value,
text: document.querySelector('.inputChat').value,
date: new Date().toLocaleString(), // 자체내장함수
roomname: document.querySelector('.inputUser').value
},app.fetch);