【问题标题】:Nuxt.js and Node.js simple form with nodemailer PROBLEM :(Nuxt.js 和 Node.js 的简单形式与 nodemailer 问题:(
【发布时间】:2021-01-08 08:03:24
【问题描述】:

我是 Nuxt.js 和 Node.js 的新手。我想在“contact.vue”页面上运行一个非常简单的联系表格。它在本地工作得很好,但是一旦我执行“npm run generate”来生成文件并将所有这些上传到 FTP,它就不再工作了。我在控制台出现错误:“POST http://website.com/api/message 404 (Not Found)”

我在表单上使用 POST 方法和指向“api / message”的操作。我在一个方法中使用 axios(在同一个 'contact.vue' 页面上:

async onSubmit (e) {
  e.preventDefault()
  await this.$axios.post('/api/message', {
    name: this.contactForm.name,
    firstname: this.contactForm.firstname,
  })
    .then((res) => {
      // On clear le formulaire
      this.contactForm.name = ''
      this.contactForm.firstname = ''
    })
    .catch((err) => {
      console.log(err)
    })
}

我在根文件夹中有一个 'api/' 文件夹,里面有 'index.js' 和代码:

const app = require('express')()
const bodyParser = require('body-parser')
const nodemailer = require('nodemailer')

module.exports = { path: '/api', handler: app }

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.post('/message', async (req, res) => {
 const contenuFormulaireContact = `
   <ul>
     <li>Nom : ${req.body.name}</li>
     <li>Prénom : ${req.body.firstname}</li>
   </ul>
 `
 // NODEMAILER
 const transporter = nodemailer.createTransport({
   host: '',
   port: 465,
   secure: true,
   auth: {
     user: '',
     pass: ''
   }
 })

 const info = await transporter.sendMail({
   from: '"Website's Name" <hello@website.com>', // sender address
   to: 'myemail@website.com', // list of receivers
   subject: `NEW MESSAGE : ${req.body.subject}`, // Subject line
   text: '', // plain text body
   html: contenuFormulaireContact // html body
 })

 console.log('Message sent: %s', info.messageId)
 console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info))

 res.redirect(200, '/contact')
 })

在我的 nuxt.config.js 中:

/*
** Nuxt.js modules
*/
modules: [
  '@nuxtjs/pwa',
  '@nuxtjs/axios'
],
/*
** Axios cfg
*/
axios: {
  baseURL: '/'
},
/*
** Server middleware
*/
serverMiddleware: ['~/api/index.js'],

如果对你们中的某些人来说,这个问题可能看起来很明显,但我完全陷入困境,我很抱歉。

非常感谢您花时间帮助我。

【问题讨论】:

    标签: node.js forms axios nuxt.js nodemailer


    【解决方案1】:

    实际上,当您运行npm run generate 时,网站变得完全静态,并且节点不再在后台运行。这就是为什么您的代码可以与 npm run devnpm run start 一起使用的原因,因为它们同时运行节点。

    我也面临同样的问题。静态网站无法从客户端发送邮件。它必须在服务器端发送。要使您的代码正常工作,您要么必须使用 node.js 服务器,要么使用 无服务器功能解决方案,例如 AWS LambdaNetlify functions,它们将执行邮件发送功能或使用外部 REST API 服务喜欢Formspree99inbound

    https://stackoverflow.com/a/53560851/2610770

    希望对你有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 2015-03-11
      • 2011-09-13
      • 1970-01-01
      相关资源
      最近更新 更多