我在Netlify上部署了一个nuxt项目,现在我想添加一个时事通讯(在Mailchimp上为我的受众添加一个订阅者(。为了实现这一点,我选择使用AWS的无服务器lambda函数。老实说,这是我第一次听说无服务器功能。我找到了这个教程https://hashinteractive.com/blog/nuxt-js-mailchimp-integration-add-contact-to-list/最后,我决定在Postman上做一个测试。我已经在http://localhost:8888/.netlify/functions/subscribe它奏效了。但当我用axios尝试同样的事情时,我得到了错误405(方法不允许(。
时事通讯.vue
<form @submit.prevent='submitNewsletter' class="newsletter__form" >
<input type="email" placeholder="E-mail" class="newsletter__form-input" v-model="email">
<button class="newsletter__form-button" type="submit">Subscribe</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data(){
return{
email: ''
}
},
methods:{
submitNewsletter(){
axios.post('http://localhost:8888/.netlify/functions/subscribe', { email: this.email}, {
headers: {
methods: 'POST',
'Content-Type':'application/json'
}
})
.then(function (response) {
console.log(response);
}).
catch((error) =>{
console.log('The error:' + error)
})
this.$toasted.success("Thank you for your subscription !!!", {
theme: "toasted-primary",
position: "top-left",
containerClass: 'myContainer',
fitToScreen: true,
fullWidth: true,
duration : 5000
});
}
}
}
</script>
函数>订阅>subscribe.js
const fetch = require('node-fetch');
const base64 = require('base-64');
exports.handler = async (event, context) => {
// Only allow POST
if (event.httpMethod !== 'POST') {
return { statusCode: 405, body: 'Method Not Allowed' };
}
const errorGen = msg => {
return { statusCode: 500, body: msg };
};
try {
const { email } = JSON.parse(event.body);
console.log(email);
if (!email) {
return errorGen('Missing Email');
}
const subscriber = {
email_address: email,
status: 'subscribed',
};
console.log(subscriber);
console.log(JSON.stringify(subscriber));
const creds = `blooming-thoughts:${process.env.MAILCHIMPS_API_KEY}`;
const response = await fetch(`https://us20.api.mailchimp.com/3.0/lists/${process.env.AUDIENCE_ID}/members/`, {
method: 'POST',
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
Authorization: `Basic ${base64.encode(creds)}`, },
body: JSON.stringify(subscriber),
});
const data = await response.json();
if (!response.ok) {
// NOT res.status >= 200 && res.status < 300
return { statusCode: data.status, body: data.detail };
}
return {
statusCode: 200,
body: JSON.stringify({ msg: "You've signed up to the mailing list!", detail: data, }),
};
} catch (err) {
console.log(err); // output to netlify function log
return {
statusCode: 500,
body: JSON.stringify({ msg: err.message }),
};
}
};
我的netlify.toml
[build]
publish = "dist"
functions = 'functions'
我已经推送了我的存储库,并在没有任何错误的情况下构建了netlify,但当我试图从我的网站添加时事通讯时,什么也没发生。
我已经解决了我的问题。如果你遇到了像我一样的麻烦,请按照以下步骤操作:
-
在根目录中创建一个名为functions的文件夹,然后创建一个index.js(文件名由您决定(。
-
创建一个名为netlify.toml的文件,并添加以下代码:
[构建]函数=";函数";
-
然后,在你的index.js中,代码将与你的API 通信
-
在vue组件上,向
<your-site>
/.netlify/functions/index发出post请求。您可以在netlify-dashbord上找到指向函数的端点。
不要忘记在Netlify(构建和部署(上注册您的env变量,仅此而已。