首页 > 解决方案 > 在位置 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));

但无法从中获得更多信息。

我将非常感谢您的一些知识,请

标签: javascriptnode.jsjsonexpressnodemailer

解决方案


你可以试试下面的代码,看看你是否在控制台中得到了一些有用的东西?

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()而不是多方。


推荐阅读