我正在用 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 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 将 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) })
});
}
对不起,很长的问题。我真的很感谢你的时间和你的帮助。如果您需要任何进一步的细节,请告诉我。