首页 > 解决方案 > 无法获取 ajax 表单数据以使用 nodemailer 提交

问题描述

大家早上好,我已经使用 node.js 和 express 制作了一个 web 应用程序。我让 Nodemailer 发送电子邮件,而我的 AJAX 正在发送解析的 JSON 数据以表达,但我无法将数据从数据中获取到 nodemailer。我的 Ajax 正在发送 JSON 来表达我已经用 DEV 工具确认了这一点,但是我不知道如何将 JSON 放入 nodemailer。任何帮助将非常感激。

/* contact Route: contact.js */
var express = require('express');
const contact = express.Router();
var path = require('path');
const bodyParser = require('body-parser');
var nodemailer = require('nodemailer');

contact.use(bodyParser.json() );
contact.use(express.static(__dirname + 'portfolio'));

contact.get('/contact',  (req,res,next) => {
  res.sendFile(path.join(__dirname, '../html-files', 'contact.html'));
  console.log('this works');
});



contact.post('/contact', (req,res) => {



  /*const data = req.body.data;
const from = data.email;
const text = data.message;*/


  var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: 'augustshah@02pilot.com',
      pass: 'hgahalzecelxdxis'
    }
  });
  
  var mailOptions = {
    from: this.email,
    to: 'augustshah@02pilot.com',
    subject: 'Quote',
    text: this.message
  };
  
  transporter.sendMail(mailOptions, function(error, info){
    if (error) {
      console.log(error);
    } else {
      console.log('Email sent: ' + info.response);
    }
  });
  
})







module.exports = contact;



/* Jquery: script.js*/
//const { json } =  require("body-parser");
//var requirejs = require('requirejs');
//const { json } = require("body-parser");




$('#submit').on('click', function(e) {
    e.preventDefault(); 

    const name = $("#name").val();
    const email = $("#email").val();
    const message = $("#message").val();
    
    var $form = $( this ),
    url = $form.attr( "action", "/contact");

    const data = {
        name: name, 
        email: email,
        message: message
    };
    
    $.ajax({
        type: "POST", // HTTP method POST or GET
        url: "/contact", //Where to make Ajax calls
        dataType: "json", // Data type, HTML, json etc.
        data: JSON.stringify(data), //Form variables
        success: function() {
             alert("Your Email has been sent");
        },
        error: function() {
            alert("Your Email has not sent. Try Again. ");
        }
    
    })

    
}); 

标签: javascriptjquerynode.jsajaxexpress

解决方案


修正:这很简单。在我的 script.js 中,我没有设置 contentType。我将其设置为“应用程序/json”并解决了我的问题。


推荐阅读