modify example client to be API compliant

This commit is contained in:
2025-05-25 13:32:29 -04:00
parent fa5d1e2689
commit 5ac529ce26
4 changed files with 25 additions and 6 deletions

View File

@@ -6,7 +6,7 @@
"scripts": { "scripts": {
"build": "rollup -c", "build": "rollup -c",
"dev": "rollup -c -w", "dev": "rollup -c -w",
"start": "sirv public --no-clear" "start": "sirv public --single"
}, },
"devDependencies": { "devDependencies": {
"@rollup/plugin-commonjs": "^24.0.0", "@rollup/plugin-commonjs": "^24.0.0",

View File

@@ -3,7 +3,17 @@ import axios from 'axios';
const API_BASE_URL = 'http://localhost:3000'; const API_BASE_URL = 'http://localhost:3000';
export const login = async (username, password) => { export const login = async (username, password) => {
const response = await axios.post(`${API_BASE_URL}/login`, { username, password }); const formData = new FormData();
formData.append('username', username);
formData.append('password', password);
const response = await axios.post(`${API_BASE_URL}/login`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
withCredentials: true,
});
return response.data; return response.data;
}; };
@@ -13,6 +23,14 @@ export const fetchMessages = async () => {
}; };
export const createMessage = async (body) => { export const createMessage = async (body) => {
const response = await axios.post(`${API_BASE_URL}/messages/new`, { body }, { withCredentials: true}); const formData = new FormData();
formData.append('body', body);
const response = await axios.post(`${API_BASE_URL}/messages/new`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
withCredentials: true,
});
return response.data; return response.data;
}; };

View File

@@ -1,5 +1,6 @@
<script> <script>
import { login } from '../api.js'; import { login } from '../api.js';
import { push } from 'svelte-spa-router';
let username = ''; let username = '';
let password = ''; let password = '';
let error = ''; let error = '';
@@ -7,9 +8,9 @@
const handleLogin = async () => { const handleLogin = async () => {
try { try {
await login(username, password); await login(username, password);
window.location.href = '/messages'; push('/messages');
} catch (err) { } catch (err) {
error = 'Invalid username or password'; error = err;
} }
}; };
</script> </script>

View File

@@ -19,7 +19,7 @@
<h1>Messages</h1> <h1>Messages</h1>
<ul> <ul>
{#each messages as message} {#each messages as message}
<li>{message.body} - {message.timestamp}</li> <li>{message.user.name} - {message.body} - {message.timestamp}</li>
{/each} {/each}
</ul> </ul>
<input type="text" bind:value={newMessage} placeholder="New message" /> <input type="text" bind:value={newMessage} placeholder="New message" />