1

我正在用 Gridsome 建立一个个人网站。我正在尝试通过 Netlify Forms 设置时事通讯注册表单。我不希望用户在单击“提交”后被重定向。为了防止我@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 guideCSS-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 将 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) })
    });
}

对不起,很长的问题。我真的很感谢你的时间和你的帮助。如果您需要任何进一步的细节,请告诉我。

4

1 回答 1

1

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

提交-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>
            `)
        }
    }
}
于 2020-08-06T20:40:01.183 回答