Currently, I am in the process of developing my personal website using Gridsome. My goal is to incorporate a newsletter signup form through Netlify Forms without redirecting the user upon clicking 'Submit'. To achieve this, I utilize @submit.prevent
as shown below:
<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>
Following instructions from resources such as the Gridsome guide and CSS-Tricks guide, I implement the following code 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 Encountered
Despite my efforts, I am facing challenges in configuring the desired behavior. The persistent errors include - >
Error: Request failed with status code 404
& Cannot POST /
Note to Consider
The rationale behind my approach is that upon form submission, a Netlify Function will trigger to forward the email address to EmailOctopus utilizing their API.
This is what the function entails:
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) })
});
}
I apologize for the length of this question. I genuinely appreciate your time and assistance. Please feel free to request additional information if needed.