【发布时间】:2021-09-28 12:24:50
【问题描述】:
我正在使用服务器中间件来处理来自联系表单的 POST。
问题是,我创建的中间件文件似乎没有运行。我使用 VS Code 添加了断点,它们不会在 contact.js 中触发,但它们会在 contact.vue 中触发(在 VS Code 中,我确保在适当的客户端/服务器端环境中添加断点)。甚至我在contact.js 中的控制台日志信息也没有出现。好像文件丢失了。
发生的情况是发出 POST 调用并保持打开状态,但没有响应。 POST 的属性和值都在那里。
我怀疑 createTransport({sendmail: true}) 失败,因为我的开发系统上没有 sendmail,但没有抛出错误。
你能看看我有什么遗漏吗?我想做的只是在提交表单时发送一封电子邮件,但这似乎很难!
我被https://blog.lichter.io/posts/emails-through-nuxtjs/指导
所有软件包都已安装。
我就是这样设置的...
nuxt.config.js
export default {
.
.
.
serverMiddleware: [
'~/api/contact'
],
.
.
.
}
pages/contact.vue
<template>
.
.
.
<form class="form-email row mx-0"
data-success="Thanks for your enquiry, we'll be in touch shortly."
data-error="Please fill in all fields correctly."
@submit.prevent="submitForm">
<div class="col-md-6 col-12 text-xl"> <label>Your Name:</label> <input v-model="name" type="text" name="name"
class="validate-required"> </div>
<div class="col-md-6 col-12 text-xl"> <label>Email Address:</label> <input v-model="email" type="email" name="email"
class="validate-required validate-email"> </div>
<div class="col-md-12 col-12 text-xl"> <label>Message:</label> <textarea v-model="message" rows="4" name="message"
class="validate-required"></textarea> </div>
<div class="col-md-5 col-lg-4 col-6"> <button type="submit" class="btn btn--primary type--uppercase">Submit</button> </div>
</form>
.
.
.
</template>
<script>
export default {
data () {
return {
name: '',
email: '',
message: ''
}
},
mounted() {
mr.documentReady($);
mr.windowLoad($);
},
methods: {
async submitForm () {
try {
await this.$axios.$post('', {
name: this.name,
email: this.email,
msg: this.message
});
await new Promise(resolve => setTimeout(resolve, 2500));
} catch (e) {
console.error(e);
}
}
}
}
</script>
api/contact.js
const express = require('express')
const nodemailer = require('nodemailer')
const validator = require('validator')
const xssFilters = require('xss-filters')
const app = express()
app.use(express.json())
app.get('/', function (req, res) {
res.status(405).json({ error: 'sorry!' })
})
app.post('/', function (req, res) {
const attributes = ['name', 'email', 'message'] // Our three form fields, all required
// Map each attribute name to the validated and sanitized equivalent (false if validation failed)
const sanitizedAttributes = attributes.map(n => validateAndSanitize(n, req.body[n]))
// True if some of the attributes new values are false -> validation failed
const someInvalid = sanitizedAttributes.some(r => !r)
if (someInvalid) {
// Throw a 422 with a neat error message if validation failed
return res.status(422).json({ 'error': 'Ugh.. That looks unprocessable!' })
}
sendMail(...sanitizedAttributes)
res.status(200).json({ 'message': 'OH YEAH' })
})
module.exports = {
path: '/api/contact',
handler: app
}
const validateAndSanitize = (key, value) => {
const rejectFunctions = {
name: v => v.length < 4,
email: v => !validator.isEmail(v),
message: v => v.length < 25
}
// If object has key and function returns false, return sanitized input. Else, return false
return rejectFunctions.hasOwnProperty(key) && !rejectFunctions[key](value) && xssFilters.inHTMLData(value)
}
const sendMail = (name, email, message) => {
console.info('Info: ????'
+'\n Contact page submission.'
+'\n Date: '+ new Date().toLocaleTimeString() +' '+ new Date().toLocaleDateString()
+'\n Name: '+ name
+'\n Email: '+ email
+'\n Message: '
+'\n'
+'\n'+ message
+'\n'
+'\n End of submission.'
+'\n');
let transporter = nodemailer.createTransport({
sendmail: true,
newline: 'unix',
path: '/usr/sbin/sendmail'
})
transporter.sendMail({
from: email,
to: 'mail@foobar.com',
subject: 'Foo Bar: Contact Form',
text: message
}, (err, info) => {
console.log(info.envelope);
console.log(info.messageId);
})
}
【问题讨论】:
-
我什至尝试使用正斜杠将其更改为
await this.$axios.$post('/', { -
如果您没有安装 sendmail,可能值得切换到基于 SMTP 的方法。随意从github.com/Developmint/developmint.de/blob/master/functions/… 中汲取灵感
标签: javascript node.js vue.js vuejs2 nuxt.js