import 'regenerator-runtime/runtime'; import axios from 'axios'; import $ from 'jquery'; import cookie from 'js-cookie'; const LOGIN_API_URL = 'http://localhost:4000'; const POSTGREST_API_URL = 'http://localhost:3000'; $('a#logout').click(function(event) { event.preventDefault(); cookie.remove('jwt'); alert('Logged out.'); }); // fetch data from postgrest $('button#fetchTodosBtn').click(async function() { $('div#todos').html(''); const jwt = cookie.get('jwt'); try { const resp = await axios.get(`${POSTGREST_API_URL}/todos`, { headers: { Authorization: `Bearer ${jwt}` }, }); const todos = resp.data; if (todos.length === 0) { $('div#todos').html('No TODOs.'); } else { todos.forEach(todo => { $('div#todos').append(`
id: ${todo.id}, task: ${todo.task}
`); }); } } catch (err) { $('div#todos').html(String(err)); alert(err); } }); $('form#loginForm').submit(async function(event) { event.preventDefault(); const username = $(this).find('input#username').val(); const password = $(this).find('input#password').val(); try { const resp = await axios.post(`${LOGIN_API_URL}/login`, { username, password }); const payload = resp.data; const jwt = payload.jwt; cookie.set('jwt', jwt); alert(`Logged in as ${username}.`); } catch (err) { cookie.remove('jwt'); alert(err); } });