Vue (Gridsome) App encountering 'Cannot POST /' error due to Netlify Forms blocking redirect functionality

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.

Answer №1

To view the functional implementation, you can check out my repository at (https://github.com/rasulkireev/gridsome-personal-webite). These are the modifications I have made.

submission-created.js

var axios = require("axios")

exports.handler = async function(event, context) {

    const email = JSON.parse(event.body).payload.email
    console.log(`Recieved a submission: ${email}`)

    return await axios({
        method: 'POST',
        url: 'https://api.buttondown.email/v1/subscribers',
        headers: {
            Authorization: `Token ${process.env.BUTTONDOWN_API}`
        },
        data: {
            'email': email,
        },
    })
    .then(response => console.log(response))
    .catch(error => console.log(error))
}

newsletter form in my components

 <div>
          <form
          name="add-subscriber"
          id="myForm"
          method="post"
          data-netlify="true"
          data-netlify-honeypot="bot-field"
          enctype="application/x-www-form-urlencoded"
          @submit.prevent="handleFormSubmit">
            <input type="hidden" name="form-name" value="add-subscriber" />
            <input type="email" name="userEmail" v-model="formData.userEmail">
            <button type="submit" name="button">Subscribe</button>
          </form>
        </div>

with the following script code in the same component

import axios from "axios";
export default {
    props: ['title', 'description'],
    
    data() {
        return {
            formData: {
                userEmail: null,
            },
        }
    },
    methods: {
        encode(data) {  
            const formData = new FormData();
            
            for (const key of Object.keys(data)) {
                formData.append(key, data[key]);
            }
            
            return formData;
        },
        handleFormSubmit(e) {
            const axiosConfig = {
                header: { "Content-Type": "application/x-www-form-urlencoded" }
            };
            axios.post(
                location.href, 
                this.encode({
                    'form-name': e.target.getAttribute("name"),
                    ...this.formData,
                }),
                axiosConfig
            )
            .then(data => console.log(data))
            .catch(error => console.log(error))
            .then(document.getElementById("myForm").innerHTML = `
            <div>Thank you! I received your submission.</div>
            `)
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying an array of errors in Vue.js can be done easily by using backend validation with Laravel

I am struggling with displaying the validation error array data in my Vue file due to the complex nature of the data. The issue arises when I try to show data that has an index and is displayed as contacts.0.name: ["...."]. Any suggestions on how ...

Issues with NodeJS's "readline" module causing prompts not to be displayed

Recently, I decided to have some fun by creating a 'note' manager using NodeJS. However, I ran into an issue when trying to use readline.question() to prompt the user for their input on managing notes. The prompt was not being displayed as expect ...

Using CSS on a randomly selected div that is chosen after dividing the main div each time it is clicked

Imagine a square box displayed as a "div" element. When you click on it, it splits into an n x n grid with each square having a random background color. However, the issue I am encountering is that I want to apply additional CSS to each of these randomly c ...

employing express.json() post raw-body

Within my Express application, I am aiming to validate the length of the request body and restrict it irrespective of the content type. Additionally, I wish to parse the body only if the content type is JSON. How can I go about accomplishing this? Curren ...

Can we verify if this API response is accurate?

I am currently delving into the world of API's and developing a basic response for users when they hit an endpoint on my express app. One question that has been lingering in my mind is what constitutes a proper API response – must it always be an o ...

What could be causing the erratic jumping behavior of the "newsletter sign-up" form within my modal dialog window?

On the homepage, there is a modal window that appears upon every pageload (it will be changed later), however, there seems to be an issue with the 'email sign up' form inside the window. The form seems to momentarily display at the top of the si ...

What is the function of async in Next.js when triggered by an onClick

Need help with calling an async function pushData() from a button onClick event async function pushData() { alert("wee"); console.log("pushing data"); try { await query(` //SQL CODE `); console.log("Done&quo ...

What is the best method for implementing click functionality to elements that share a common class using only pure JavaScript

I am struggling to figure out how to select specific elements with the same classes using only pure JavaScript (no jQuery). For example: <div class="item"> <div class="divInside"></div> </div> <div class= ...

Adjusting the Stripe Button to Utilize a Unique Button Class

I have a stripe button on my website and I want to add my custom class to it. I discovered that manually creating the CSS for it can work, but I prefer to maintain consistency across all buttons on my site by using my custom class. No matter what I attemp ...

Sequelize makes it easy to input records into various tables simultaneously

Embarking on my first experience with Sequelize and MySQL, I am seeking guidance on inserting data into two tables with a foreign key relationship. Let's delve into the structure of the entities - bookingDescription and bookingSummary. //bookingSumma ...

Is there a glitch in the three.js loadOBJMTL loader?

Encountering an issue with the OBJMTL loader in three.js. I'm working with obj/mtl/jpeg files and getting load errors that look like this: "THREE.OBJMTLLoader: Unhandled line 4033/5601/6659" OBJMTLLoader.js:347 Seems like there is a problem with a c ...

Allowing the contenteditable attribute to function only on a single line of

My app allows users to create different lists, with the ability to edit the name. However, I am facing an issue where if a user types a new name, it should remain on only one line. I tried adding max height and overflow hidden properties, but it only hides ...

I am unable to access the properties of an undefined element, specifically the 'size' property in Next.js 13

I encountered a problem today while working with Next.js version 13.4 and backend integration. When using searchParams on the server side, I received an error message: "Cannot read properties of undefined (reading 'size')" while destructuring siz ...

JavaScript: Retrieving the following element from the parent container

Is there a way to prevent the next element within the parent tag from being enabled or disabled based on a certain condition? HTML: <span> <input type="checkbox" onchange="toggleInput(this)"> </span> <input type="text" ...

Show Particular Outcome at the Beginning of Array in ReactJS

I am working with an array of data that contains a list of names, and I need to sort it so that a specific name ("Fav Team") always appears at the top of the list. The array has two fields, homeTeamName and awayTeamName, that may contain this value. How ...

Notification for background processing of $http requests

I am searching for a solution to encapsulate all my AJAX requests using $http with the capability to display a loading gif image during processing. I want this functionality to extend beyond just $http requests, to cover other background processing tasks a ...

Is it possible to change sidebars in a spreadsheet if you are not a member of Google Workplace?

I am currently working on developing a Google Spreadsheet Add-on using GAS. I intend to switch between sidebars by utilizing the HtmlService class method. Here is the code snippet that I have implemented: function showSidebarA() { const ui = HtmlService ...

React-Native introduces a new container powered by VirtualizedList

Upon updating to react-native 0.61, a plethora of warnings have started appearing: There are VirtualizedLists nested inside plain ScrollViews with the same orientation - it's recommended to avoid this and use another VirtualizedList-backed container ...

Conceal only the anchor tag's text and include a class during the media query

In the anchor tag below, I have a text that says "Add to cart," but on mobile view, I want to change it to display the shopping cart icon (fa fa-cart). <a class="product"><?php echo $button_add_to_cart ?></a> Currently, the variable $bu ...

3 Methods for Implementing a Floating Header, Main Content, and Sidebar with Responsive Design

I am following a mobile-first approach with 3 containers that need to be displayed in 3 different layouts as shown in the image below: https://i.sstatic.net/UjKNH.png The closest CSS implementation I have achieved so far is this: HTML: <header>.. ...