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

Navigating through JSON data to retrieve specific values and executing repetitive actions

When the form is submitted, I am making an AJAX request to PHP code and this is the response I receive. var data = { "empty":{ "game_sais_no":"Season cannot contain empty value", "game_sc_no":"Category cannot contain empty value", ...

Vue for Number Crunching

Learning vueJS is quite new to me. I am attempting to capture two input values, add them together, and display the result. I have encountered a strange issue where when subtracting number1 from number3, multiplying number1 with number2, or dividing number ...

Exploring the capabilities of zooming on SVG elements using D3 within an Angular

I want to implement pan/zoom functionality on an SVG element. I came across a tutorial that suggested using d3.js for this purpose, you can find it here Below is the code I have tried: import { Component,AfterViewInit,OnInit } from '@angular/core&a ...

Encountering a sudden problem while running gulp build due to a node_module - Surprising occurrence of Unexpected

Encountering an unexpected issue while running a gulp build process for a web app that I am struggling to resolve. The problem did not exist on the evening of 25/01/2019, but when attempting to execute the gulp build process this morning (30/01/2019), an ...

Difficulty in toggling the visibility of the react-date-range picker package when selecting a date

I need assistance with a problem I'm facing. I am having trouble hiding and showing the react-date-range picker upon date selection. The issue is related to a package that I am using for date range selection. You can find the package link here - https ...

Exploring the Brilliance of MVC PHP/AJAX

I am currently in the process of developing a PHP website that will showcase statistics derived from an external source. To illustrate how the MVC (Model-View-Controller) architecture will be implemented, I have created this unique diagram. As someone wh ...

Enable vertical scrolling on the second row of a table while keeping the first row fixed as the table header (CSS)

While embedding the Ace Editor in a Chrome popup window, I encountered a challenge. My goal was to keep the first row of text always visible at the top while allowing the rest of the Editor to fill the screen. However, there is an issue with a vertical scr ...

It is not feasible to establish a personalized encoding while sending a post request through XMLHTTPRequest

When using the JS console in the latest version of Chrome browser, I encountered the following issue: x = new XMLHttpRequest(); x.open('POST', '?a=2'); x.setRequestHeader('Content-Type', 'application/ ...

What could be causing the Universal Code for Disqus to not function properly?

Struggling to get this code to work on my website. I've tried everything, from clearing caches and cookies to disabling plugins and extensions, but still no luck. Check out the code below: import React, { Component } from 'react' import { ...

Utilize time in submitting a form

Is it possible to schedule a form submission at a specific time, such as 12:00? I have already created a countdown timer and now would like the form to be submitted automatically at a certain time. <html> <head> </head> <body> ...

Manipulate Nested Objects using an Array of Keys

Currently, I am developing a recursive form using React and MUI that is based on a nested object. Throughout this process, it is crucial for me to keep track of the previous keys as I traverse through the recursion. As users interact with the form and mak ...

Testing a React component using the `ua-parser-js` plugin with Jest and React Testing Library

I've developed a simple component that displays an image depending on the operating system you are using (in this case, iOS and Android). import { UAParser } from "ua-parser-js"; export const DownloadApp = ({ appleStoreUrl, playStoreUrl }: ...

Having difficulty integrating a Hangout button using APIs on my webpage

I'm having some trouble adding a basic Hangout button component to initiate Google's Hangout. I've been following the steps outlined on the Google Developer page, but despite my efforts, I can't seem to resolve the following issue: Fai ...

The node.js oauth-1.0a implementation is successful in authenticating with Twitter API v1.1, however, it encounters issues

Having come across this function for generating an oauth-1.0a header: // auth.js const crypto = require("crypto"); const OAuth1a = require("oauth-1.0a"); function auth(request) { const oauth = new OAuth1a({ consumer: { key ...

Learn how to retrieve specific user information from a JSON file by implementing a button click feature within a custom directory using Angular.js

I am just starting to learn angular.js and I'm trying to figure out how to retrieve JSON data from a custom directory. My goal is to display the information of a specific user when a particular button is clicked, but so far I haven't been success ...

Unable to launch React Native project on emulator now

Something seems off with my App as it won't start up on my AS Emulator. Everything was running smoothly yesterday, but today it's not working - possibly due to me moving the npm and npm-cache folders, although they are configured correctly with n ...

Could it be feasible to manage several ongoing asynchronous requests simultaneously?

Visualize a grid in which the user completes cell A1 and presses Enter to move to A2. As this happens, a request is sent to the backend to search a database and retrieve results for populating the remaining cells in row A. Meanwhile, I want the user to con ...

What is the best way to organize a table with multiple state variables using nested loops?

What is the best way to display multiple variables in a table using a loop, such as i,j,k? this.state = { materials: ['m1', 'm2'], quantity: ['2', '4'], unitPrice : ['12&apo ...

What are the steps to installing and utilizing the Chart.js package on your local machine?

I thought installing chart.js on my Raspberry Pi would be a simple task, but I seem to be struggling with it. Due to the nature of my project, I need to have it installed locally rather than relying on an online version. Following the usual steps, I navig ...

Switching from ejs format to html

I've been working on a tutorial that uses ejs, but I'm not too familiar with it. I'd like to know how to convert the server.js from using ejs to html. Here's the code snippet: app.set('view-engine', 'ejs') app.use( ...