vue.js 我不能通过nuxt 3中的nodemailer发送表单

k2fxgqgv  于 12个月前  发布在  Vue.js
关注(0)|答案(1)|浏览(116)

我的contact.post.js在服务器/API目录。我已经试图通过 Postman 发布它,但现在smth出错,我得到了500错误。POST http://localhost:3000/api/contact [HTTP/1.1 500内部服务器错误19毫秒]。我真的不知道该怎么办,希望任何人都能帮助我

import nodemailer from 'nodemailer';
import validator from 'validator';
const config = useRuntimeConfig();

const transporter = nodemailer.createTransport({
    host: config.MAILHOST,
    port: config.MAILPORT,
    auth: {
        user: config.MAILUSER,
        pass: config.MAILPASSWORD,
    },
});

export default defineEventHandler(async (event) => {
    try {
        const body = await readBody(event);

        await isValid(body)
            .then(async (data) => {
                const mail = await transporter.sendMail({
                    form: `"${data.name}" <${data.email}>`,
                    to: config.CONTACTMAIL,
                    subject: data.comment,
                    text: data.comment,
                    html: data.message,
                });

                console.log('Message sent: %s', mail.messageId);
                console.log('Preview URL: %s', nodemailer.getTestMessageUrl(mail));
                return Promise.resolve();
            })
            .catch((errors) => {
                return Promise.reject(errors);
            });

        return 'Gesendet!';
    } catch (error) {
        sendError(event, createError({ statusCode: 400, statusMessage: error }));
    }
});

async function isValid(body) {
    const errors = [];

    if (validator.isEmpty(body.name || ''))
        errors.push({
            field: 'name',
            error: 'Field is required.',
        });
    if (validator.isEmpty(body.phone || ''))
        errors.push({ 
        field: 'phone', 
        error: 'Field is required.'
     });
    if (validator.isEmail(body.email || ''))
        errors.push({ 
        field: 'email',
        error: 'Field is required.' 
    });
    if (validator.isEmpty(body.budget || ''))
        errors.push({ 
        field: 'budget',
        error: 'Field is required.' 
    });
    if (!validator.isEmpty(body.comment || ''))
        errors.push({ 
        field: 'comment', 
        error: 'Field should be a valid .' 
    });

    if (errors.length > 0) {
        return Promise.reject(errors);
    } else {
        return Promise.resolve({
            email: validator.normalizeEmail(body.email),
            name: validator.escape(body.name),
            phone: validator.escape(body.phone),
            budget: validator.escape(body.budget),
            comment: validator.escape(body.comment),
        });
    }
}

字符串
和形式的组成部分。vue什么也没发生

<template>
  <div class="m-3 lg:m-1">
    <form @submit.prevent="submit(form)">
      <div id="form" class="flex tad">
        <div class="forma w-1/3 m-8">
          <h1 class="text-volna send text-4xl mb-3">Оставь заявку</h1>
          <div action="" method="POST">
            <p class="text-white">Ваше ФИО</p>
            <input
              v-model="form.name"
              name="name"
              class="inp"
              type="text"
              placeholder="введите ваше имя"
            />
            <p class="text-white">Ваш номер телефона</p>
            <input
              v-model="form.phone"
              name="phone"
              class="inp"
              type="text"
              placeholder="Ввведите номер для связи с вами"
            />
            <p class="text-white">Ваш email</p>
            <input
              name="email"
              v-model="form.mail"
              class="inp"
              type="email"
              placeholder="введите контактный email"
            />
          </div>
        </div>
        <div class="forma w-1/3 m-8">
          <div class="sec_forma">
            <div class="">
              <p class="text-white">Ваш бюджет</p>
              <input
                v-model="form.budget"
                name="money"
                class="inp"
                type="text"
                placeholder="введите ваш бюджет"
              />
              <p class="text-white">Введите Ваш комментарий (по желанию)</p>
              <input
                v-model="form.comment"
                name="comment"
                class="inp"
                type="text"
                placeholder=" ваш комментарий"
              />
              <button
                @click="submit(form)"
                type="submit"
                class="button button-1 mb-3"
              >
                отправить
              </button>
            </div>
          </div>
        </div>
           
      </div>
    </form>
  </div>
</template>

<script setup>
const form = ref({
  name: '',
  phone: '',
  email: '',
  budget: '',
  comment: '',
});

const errors = ref(false);
const success = ref(false);
const waiting = ref(false);

async function submit(form) {
  waiting.value = true;
  await $fetch('http://localhost:3000/api/contact', {
    method: 'POST',
    body: JSON.stringify(form.value),
  }).then(() => {
    errors.value = false;
    success.value = true;
    waiting.value = false;
    form.value = {
      name: '',
      phone: '',
      email: '',
      budget: '',
      comment: '',
    };
    
  }).catch(() => {
    errors.value = true;
    success.value = false;
    waiting.value = false;
  });
}

</script>

5cg8jx4n

5cg8jx4n1#

在你的代码中,你使用.then()和.catch()来处理promise。确保任何未处理的promise拒绝都被正确捕获和记录。你可以添加一个全局unhandledRejection事件处理程序来捕获未处理的promise拒绝并记录它们:
process.on('unhandledRejection',(reason,promise)=> {
console.error('Unhandled Rejection at:',promise,'reason:',reason); });

相关问题