I'm trying to implement a feature where every time a user types into an input field, an API request is made, and the results are displayed directly below the input. It's similar to a typeahead or autocomplete functionality. While I could potentially make the request directly from the client and display the results, I need to handle the API request on the server side. This is because all requests must include a token in the header, and the cookie where the token is stored is set to httpOnly:true. Thus, I cannot access this cookie from the client side. Can someone guide me on how to achieve this? Any advice is welcome. Thank you
<script lang="ts">
import { Button, Input, Label } from 'flowbite-svelte';
export let data;
let taskId = '';
const onChange = async () => {};
</script>
<div class="max-w-screen-md mx-auto p-6 space-y-8">
<div class="bg-white shadow-md rounded-lg p-6">
<div class="text-center mb-8">
<h2 class="text-2xl bold">Task Form</h2>
</div>
<div class="relative">
<Label class="block mb-1">Task ID</Label>
<Input
label="Email"
id="email"
name="email"
bind:value={taskId}
on:change={onChange}
required
placeholder="Task id..."
/>
<br />
<Label class="block mb-1">유저 닉네임</Label>
<Input label="nickname" id="nickname" name="nickname" required placeholder="nickname..." />
</div>
</div>
<Button type="submit">Create</Button>
</div>
Problem Statement: I aimed to implement a feature where every time a user inputs into a field, an API request is triggered, and the results are displayed right below the input. It's crucial to note that the API request needs to be handled server-side, not directly from the client. This is due to the necessity to include a token in the request header, which is stored in a cookie set to httpOnly: true. Thus, it's inaccessible from the client side.
Client-side Code:
To avoid making an immediate API request upon every keystroke, I employed a debounce functionality. This ensures the function only gets executed after the user has stopped typing for a specified duration. I manage the input values for both taskId and nickname using separate state variables. On each input, the debounce-wrapped API call functions,
_handleTaskInputand_handleNicknameInput, are invoked. The results are stored in taskResults and nicknameResults and are subsequently displayed to the user.Server-side Code:
This segment of the code handles the request sent from the client. It processes the POST request for the /api/task endpoint. The taskId value is extracted from the request body and based on it, a mock result data is generated and returned. In a real-world scenario, this section would typically query an external API or database to fetch the actual data.
Here's my code.