javascript - 无法获取 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. ");
}
})
});
解决方案
修正:这很简单。在我的 script.js 中,我没有设置 contentType。我将其设置为“应用程序/json”并解决了我的问题。
推荐阅读
- unity3d - 如何放大和缩小并保持纵横比?
- c - 如何为open编写一个包装函数,它接受可变数量的参数?
- json - 如何在Angular 7中的Json序列化中添加类型信息
- c# - 在 Visual Studio for Mac 中添加 Web 引用
- android - 生成签名的 APK:构建 APK 时出错。您可以在“消息”视图中找到错误
- c# - 从 .net 中的已发布文件夹运行后,Quartz 调度程序无法正常工作
- spring-cloud-stream - Spring Cloud Aws kinesis Binder 组中的所有 JVM 以不同的时间间隔使用相同的消息
- c++-winrt - C++/WinRT 或 WinRT/ABI 是否具有 _declspec(novtable) 的 CRTP“功能”?
- java - 如何在java中生成森林
- node.js - 使许多填充深度填充,第 2 级