File size: 2,458 Bytes
2d8be8f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | <script>
import { fetch as tauriFetch } from '@tauri-apps/plugin-http'
import { JsonView } from '@zerodevx/svelte-json-view'
let httpMethod = 'GET'
let httpBody = ''
export let onMessage
async function makeHttpRequest() {
let method = httpMethod || 'GET'
const options = {
method: method || 'GET',
headers: {}
}
let bodyType
if (method !== 'GET') {
options.body = httpBody
if (
(httpBody.startsWith('{') && httpBody.endsWith('}')) ||
(httpBody.startsWith('[') && httpBody.endsWith(']'))
) {
options.headers['Content-Type'] = 'application/json'
bodyType = 'json'
} else if (httpBody !== '') {
bodyType = 'text'
}
}
const response = await tauriFetch('http://localhost:3003', options)
const body =
bodyType === 'json' ? await response.json() : await response.text()
onMessage({
url: response.url,
status: response.status,
ok: response.ok,
headers: Object.fromEntries(response.headers.entries()),
body
})
}
/// http form
let foo = 'baz'
let bar = 'qux'
let result = null
async function doPost() {
const form = new FormData()
form.append('foo', foo)
form.append('bar', bar)
const response = await tauriFetch('http://localhost:3003/tauri', {
method: 'POST',
body: form
})
result = {
url: response.url,
status: response.status,
ok: response.ok,
headers: Object.fromEntries(response.headers.entries()),
body: await response.text()
}
}
</script>
<form on:submit|preventDefault={makeHttpRequest}>
<select class="input" id="request-method" bind:value={httpMethod}>
<option value="GET">GET</option>
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="PATCH">PATCH</option>
<option value="DELETE">DELETE</option>
</select>
<br />
<textarea
class="input h-auto w-100%"
id="request-body"
placeholder="Request body"
rows="5"
bind:value={httpBody}
></textarea>
<br />
<button class="btn" id="make-request"> Make request </button>
</form>
<br />
<h3>HTTP Form</h3>
<div class="flex gap-2 children:grow">
<input class="input" bind:value={foo} />
<input class="input" bind:value={bar} />
</div>
<br />
<br />
<button class="btn" type="button" on:click={doPost}> Post it</button>
<br />
<br />
<JsonView json={result} />
|