'How do I create the URL to send a GET request for a form?
I am using this form.
<form action="http://localhost:3000/">
<input type="text"
id="url"
name="url"
v-model="url"
placeholder="http://">
<input type="text" id="message" name="message" value="888">
<button @click="submit" :disabled="disabled">Go</button>
</form>
Until now, pressing a button resulted in http:localhost:300?url=...&message=... page being fetched.
Now I am trying to manually override this, so I added e.preventDefault(); to the submit() function. Now I can call Fetch API to fetch this URL manually, but how to I construct the URL from the form?
All online sources show how to do it with POST, no one seems to cover GET. Not sure why, because I need an idempotent request. Is there a standard way of doing this?
Solution 1:[1]
You're using Vue so typically you'd use something like this
<template>
<form @submit.prevent="submit">
<input
type="text"
v-model="url"
placeholder="http://"
/>
<input
type="text"
v-model="message"
/>
<button type="submit" :disabled="disabled">Go</button>
</form>
</template>
Notes:
- The
<button>is a submit button without a click handler. This lets you listen for submit events on the<form>which can be triggered by mouse click or keyboard. - The
@submit.preventhandles the submit event on the<form>and prevents the default action automatically - All
<input>fields have an associatedv-modelbacking adataproperty
Here's an example of the <script> part
const target = "http://localhost:3000/";
export default {
data: () => ({
url: "",
message: "888",
}),
computed: {
// just an example
disabled: ({ url, message }) => url.length === 0 || message.length === 0,
},
methods: {
async submit() {
const params = new URLSearchParams({
url: this.url,
message: this.message
});
const res = await fetch(`${target}?${params}`);
},
},
};
In regular JS, you can still listen for submit events on the form, capture all the fields using FormData and turn that into a query string with URLSearchParams
document.querySelector("form").addEventListener("submit", async (e) => {
e.preventDefault();
const data = new FormData(e.target);
const params = new URLSearchParams(data);
const res = await fetch(`${e.target.action}?${params}`)
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
