Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. function knocking() {
  2. const username = 'guest';
  3. const password = 'guest';
  4. let queryValue = 'Knock Knock';
  5. const knockMessage = ' Knock again...'
  6. const baseUrl = 'https://baas.kinvey.com/appdata/kid_BJXTsSi-e/knock';
  7. const loginUrl = 'https://baas.kinvey.com/user/kid_BJXTsSi-e/login';
  8.  
  9. const loginAuthString = 'a2lkX0JKWFRzU2ktZTo0NDdiOGU3MDQ2ZjA0ODAzOWQ5NTYxMGMxYjAzOTM5MA==';
  10. const btnPush = document.querySelector('button');
  11. const h2 = document.getElementById('result');
  12.  
  13. login();
  14.  
  15. async function login() {
  16. try {
  17. const response = await fetch(loginUrl, {
  18. method: 'POST',
  19. headers: {
  20. 'Authorization': `Basic ${loginAuthString}`,
  21. 'Content-Type': 'application/json'
  22. },
  23. body: JSON.stringify({
  24. "username": username,
  25. "password": password
  26. })
  27. })
  28.  
  29. const data = await responseHandler(response);
  30. btnPush.hidden = false;
  31. const authToken = data._kmd.authtoken;
  32. btnPush.addEventListener('click', async () => {
  33. h2.textContent = '';
  34. const query = `?query=${queryValue}`;
  35. const data = await sendGetRequest(authToken, query);
  36. if (!data) {
  37. btnPush.textContent = 'Welcome!'
  38. return;
  39. }
  40.  
  41. queryValue = data.answer;
  42. h2.textContent = queryValue + knockMessage;
  43.  
  44. });
  45. } catch (err) {
  46. alert(err.message)
  47. }
  48. }
  49.  
  50. async function sendGetRequest(authToken, query) {
  51. const response = await fetch(baseUrl + query, {
  52. method: 'GET',
  53. headers: {
  54. 'Authorization': `Kinvey ${authToken}`,
  55. 'Content-Type': 'application/json'
  56. }
  57. })
  58.  
  59. return responseHandler(response);
  60. }
  61.  
  62. function responseHandler(response) {
  63. if (response.status > 400) {
  64. throw new Error(`Error: ${response.status}(${response.statusText})`);
  65. }
  66.  
  67. return response.json();
  68. }
  69. }
  70.  
  71. knocking();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement