javascript - 在位置 0 的 json 中发送表单 -unexpected token 时出错
问题描述
我第一次使用 Nodemailer 通过 Node 制作联系表格,您可以通过网站发送联系表格,然后它会直接发送到您的收件箱。
所以我在公共文件夹上的 app.js 是这样的:
const form = document.getElementById('contact-form');
const formEvent = form.addEventListener('submit', event => {
event.preventDefault();
let mail = new FormData(form);
sendMail(mail);
});
const sendMail = mail => {
fetch('https://coopza-testing.herokuapp.com/send', {
method: 'post',
body: mail,
}).then(response => response.json());
};
在我的 server.js 文件上是
const express = require('express');
const cors = require('cors');
const nodemailer = require('nodemailer');
const multiparty = require('multiparty');
require('dotenv').config();
const PORT = process.env.PORT || 5000;
// instantiate an express app
const app = express();
// cors
app.use(cors({ origin: '*' }));
app.use(express.static('public'));
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
next();
});
app.use('/public', express.static(`${process.cwd()}/public/index.html`)); // make public static
const transporter = nodemailer.createTransport({
service: 'smtp.gmail.com',
port: 587,
auth: {
user: process.env.EMAIL,
pass: process.env.PASS,
},
});
// verify connection configuration
transporter.verify(function(error, success) {
if (error) {
console.log(error);
} else {
console.log('Server is ready to take our messages');
}
});
app.post('/send', (req, res) => {
let form = new multiparty.Form();
let data = {};
form.parse(req, function(err, fields) {
console.log(fields);
Object.keys(fields).forEach(function(property) {
data[property] = fields[property].toString();
});
console.log(data);
const mail = {
sender: `${data.name} <${data.email}>`,
to: process.env.EMAIL, // receiver email,
subject: data.subject,
text: `${data.name} <${data.email}> \n${data.message}`,
};
transporter.sendMail(mail, (err, data) => {
if (err) {
console.log(err);
res.status(500).send('Something went wrong.');
} else {
res.status(200).send('Email successfully sent to recipient!');
}
});
});
});
// Index page (static HTML)
app.route('/').get(function(req, res) {
res.sendFile(`${process.cwd()}/public/index.html`);
});
/** ********************************************** */
// Express server listening...
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}...`);
});
当我发送表单时,它带有错误:
unexpected token s in json at position 0
POST https://coopza-testing.herokuapp.com/send 500 (Internal Server Error)
我在 json 中尝试过,响应
.then(res => res.text()) // convert to plain text
.then(text => console.log(text));
但无法从中获得更多信息。
我将非常感谢您的一些知识,请
解决方案
你可以试试下面的代码,看看你是否在控制台中得到了一些有用的东西?
app.post('/send', (req, res) => {
let form = new multiparty.Form();
let data = {};
form.parse(req, function(err, fields) {
if (err) {
console.error('An error has occurred while parsing the form', { err });
}
console.log({ fields });
Object.keys(fields).forEach(function(property) {
data[property] = fields[property].toString();
});
console.log({ data });
const mail = {
sender: `${data.name} <${data.email}>`,
to: process.env.EMAIL, // receiver email,
subject: data.subject,
text: `${data.name} <${data.email}> \n${data.message}`,
};
// for debugging purpose, check what values `mail` object is having
console.log({mail});
// check to see if this is causing the trouble??
console.log({json: JSON.stringify(mail)});
transporter.sendMail(mail, (err, data) => {
if (err) {
console.error('Error while sending the email', err);
res.status(500).send('Something went wrong.');
} else {
res.status(200).send('Email successfully sent to recipient!');
}
});
});
});
另外,我有一个问题要问你,你为什么使用multiparty
模块将数据解析为 json 对象,你不能使用简单的app.use(express.json(options));
吗?由于您只是使用表单来获取用于发送文本数据的 JSON 值,因此您可以使用express.json()
而不是多方。
推荐阅读
- java - 抽象类和接口类
- java - 解析日期列表以在 scala 中列出字符串
- ios - 无法从应用扩展访问本地化资源
- python - 进行多处理时“TypeError:'type' object is not subscriptable”。我究竟做错了什么?
- python - 单击带有硒库的标签的属性
- javascript - 401 Error - Call REST API secured with AZURE Active Directory (JavaScript Client)
- bixby - 如何在 bixby 中将数组项作为循环放入对话驱动程序模板中
- python - 我很困惑为什么这个递归循环不会停止
- augmented-reality - ARKit 相机欧拉角旋转顺序
- oop - 浮动没有正常显示(飞镖语言)