I am building a personal website with Gridsome. I am trying to set up a newsletter signup form via Netlify Forms. I don't want the user to be redirected after clicking 'Submit'. To prevent that I use @submit.prevent
like so:
<form name= "add-subscriber" id="myForm" method="post" @submit.prevent="handleFormSubmit"
data-netlify="true" data-netlify-honeypot="bot-field">
<input type="hidden" name="form-name" value="add-subscriber" />
<input type="email" v-model="formData.userEmail" name="user_email" required="" id="id_user_email">
<button type="submit" name="button">Subscribe</button>
</form>
Then using a mix of the following guides (gridsome guide, CSS-Tricks guide) I do the following in my script section:
<script>
import axios from "axios";
export default {
data() {
return {
formData: {},
}
},
methods: {
encode(data) {
return Object.keys(data)
.map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
.join('&')
},
handleFormSubmit(e) {
axios('/', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: this.encode({
'form-name': e.target.getAttribute('name'),
...this.formData,
}),
})
.then(() => this.innerHTML = `<div class="form--success">Almost there! Check your inbox for a confirmation e-mail.</div>`)
.catch(error => alert(error))
}
}
}
</script>
Error
Whatever I try I can't figure out how to configure the desired behavior. I keep getting the following errors - > Error: Request failed with status code 404
& Cannot POST /
Note
The reason I want to do it this way is that after the user submits the form a Netlify Function will be called to send the email_adress to EmailOctopus via their API.
This is how the function looks like:
submissions-created.js
import axios from "axios";
exports.handler = async function(event) {
console.log(event.body)
const email = JSON.parse(event.body).payload.userEmail
console.log(`Recieved a submission: ${email}`)
axios({
method: 'POST',
url: `https://emailoctopus.com/api/1.5/lists/contacts`,
data: {
"api_key": apikey,
"email_address": email,
},
})
.then(response => response.json())
.then(data => {
console.log(`Submitted to EmailOctopus:\n ${data}`)
})
.catch(function (error) {
error => ({ statusCode: 422, body: String(error) })
});
}
Sorry for the long question. I really apreciate your time and your help. If you need any further details please let me know.