Browse Source

homework13 stage6 update done

holevchuk.evgeny 1 year ago
parent
commit
eb0babf8e8
1 changed files with 34 additions and 1 deletions
  1. 34 1
      hw13/stage6.js

+ 34 - 1
hw13/stage6.js

@@ -1,4 +1,6 @@
-const jsonPost = async (url, data) => {
+// изначальный вариант решения с async/await fetch - сам не знаю зачем сделал)
+
+/*const jsonPost = async (url, data) => {
 	try {
 		const response = await fetch(url, {
 			method: 'POST',
@@ -28,4 +30,35 @@ sendButton.addEventListener('click', async () => {
 	);
 
 	console.log(newPost.nextMessageId);
+});*/
+
+const jsonPost = (url, data) => {
+	return fetch(url, {
+		method: 'POST',
+		body: JSON.stringify(data)
+	}).then(response => {
+		if (response.ok) {
+			return response.json();
+		} else {
+			throw new Error(`An error has occurred: ${response.status}`);
+		}
+	}).catch(err => {
+		console.log(err);
+	});
+}
+
+const url = "http://students.a-level.com.ua:10012";
+
+sendButton.addEventListener('click', () => {
+	let nickValue = nickInput.value;
+	let messageValue = messageInput.value;
+
+	const newPost = jsonPost(url, {
+			func: 'addMessage',
+			nick: nickValue,
+			message: messageValue
+		}
+	);
+
+	newPost.then(data => console.log(data.nextMessageId))
 });