function jsonPost(url, data) { return new Promise((resolve, reject) => { const x = new XMLHttpRequest(); x.onerror = () => reject(new Error('jsonPost failed')) //x.setRequestHeader('Content-Type', 'application/json'); x.open("POST", url, true); x.send(JSON.stringify(data)) x.onreadystatechange = () => { if (x.readyState === XMLHttpRequest.DONE && x.status === 200){ resolve(JSON.parse(x.responseText)) } else if (x.status !== 200){ reject(new Error('status is not 200')) } } }); } const url = "http://students.a-level.com.ua:10012"; let messagesArray = jsonPost(url, {func: 'getMessages'}); const addZero = data => data < 10 ? `0${data}` : data; const buildDate = date => `${date.getDate()}/${date.getMonth()+1}/${date.getFullYear()} ${addZero(date.getHours())}:${addZero(date.getMinutes())}:${addZero(date.getSeconds())}`; const buildMessage = (nick, message, time) => { return `
nick - ${nick}, message - ${message}, date - ${buildDate(new Date(time))}
`; } messagesArray.then(messages => { for (const message of messages.data) { chatMessages.insertAdjacentHTML('afterbegin', buildMessage(message.nick, message.message, message.timestamp)); } });