"Cannot POST /" 在 Vue (Gridsome) 应用程序中 - Netlify 表单阻止重定向

"Cannot POST /" in Vue (Gridsome) App - Netlify Forms prevent redirect

我正在使用 Gridsome 建立个人网站。我正在尝试通过 Netlify Forms 设置时事通讯注册表单。我不希望用户在单击 'Submit' 后被重定向。为了防止我这样使用 @submit.prevent

<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>

然后混合使用以下指南 (gridsome guide, CSS-Tricks guide) 我在脚本部分执行以下操作:

<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: Request failed with status code 404 & Cannot POST /

备注

我想这样做的原因是,在用户提交表单后,将调用 Netlify 函数通过他们的 API.[=18= 将 email_adress 发送到 EmailOctopus ]

函数如下所示:

提交-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) })
    });
}

抱歉这个问题太长了。我真的很感谢你的时间和你的帮助。如果您需要任何进一步的详细信息,请告诉我。

你可以在我的 repo (https://github.com/rasulkireev/gridsome-personal-webite) 中看到功能实现。这些是我所做的更改。

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))
}

时事通讯 form 在我的组件中

 <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>

与以下脚本代码在同一个组件中

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>
            `)
        }
    }
}