简体   繁体   English

在 position 0 的 json 中发送表单时出现错误

[英]Getting error when sending form -unexpected token s in json at position 0

I am doing for the first time a contact form through Node with Nodemailer where you send the contact form through the website and it goes straight to your inbox.我第一次使用 Nodemailer 通过 Node 制作联系表格,您可以通过网站发送联系表格,然后它会直接发送到您的收件箱。

So my app.js on the public folder is like this:所以我在公共文件夹上的 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());
  
};

And on my server.js file is在我的 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}...`);
});

When I send the form it comes with the errors:当我发送表单时,它带有错误:

unexpected token s in json at position 0
POST https://coopza-testing.herokuapp.com/send 500 (Internal Server Error)

I tried in the json, response with我在 json 中尝试过,响应

 .then(res => res.text()) // convert to plain text
    .then(text => console.log(text));

But no more info could get from it.但无法从中获得更多信息。

I would be much appreciated some knowledge of yours, please我将非常感谢您的一些知识,请

"unexpected token s in json at position 0" error comes in when you try to parse object which can't be converted to JSON. "unexpected token s in json at position 0" error comes in when you try to parse object which can't be converted to JSON.

for ex:例如:

let str = 'Test string';
console.log(JSON.parse(str)). --> will throw an error.

Just try to console it.试着安慰它。 Also try to use debugger or console to check till where the code is executing without errors, you can see through it.还可以尝试使用调试器或控制台检查代码执行的位置没有错误,您可以看穿它。

let form = new multiparty.Form();
  let data = {};
  console.log(form);
  form.parse(req, function(err, fields) <- this parsing could be a problem

Can you try the following code and see if you get something useful in the console?你可以试试下面的代码,看看你是否在控制台中得到了一些有用的东西?

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!');
      }
    });
  });
});

Also, I have a question for you, why are you using the multiparty module for parsing data as json object, can't you use a simple app.use(express.json(options));另外,我有一个问题要问你,你为什么使用multiparty模块来解析数据为 json object,你不能用一个简单的app.use(express.json(options)); ? ? As you're just using the form to get the JSON value for sending textual data, then you could have used express.json() instead of multiparty.由于您只是使用表单获取 JSON 值来发送文本数据,因此您可以使用express.json()而不是多方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从asyncStorage获取时的JSON.parse(object)引发错误:位置1的JSON中的意外令牌o - JSON.parse(object) when getting from asyncStorage throws error: Unexpected token o in JSON at position 1 错误:位置 0 处的 JSON 中出现意外标记 &lt; - Error: Unexpected token < in JSON at position 0 为什么我在 JSON 中的位置 0 处收到 Unexpected token &lt; 的错误 - Why am I getting an error of Unexpected token < in JSON at position 0 获取错误:-S SyntaxError: Unexpected token &lt; in JSON at position 0 REACT - Fetch Error :-S SyntaxError: Unexpected token < in JSON at position 0 REACT HttpErrorResonse JSON 中的意外令牌 S 在 position 0 Firebase - HttpErrorResonse Unexpected token S in JSON at position 0 Firebase SyntaxError:JSON中位置1处的意外令牌s - SyntaxError: Unexpected token s in JSON at position 1 JSON. 解析 position 0 处的意外令牌 - JSON.parse unexpected token s at position 0 SyntaxError:位置17的JSON中的意外令牌S - SyntaxError: Unexpected token S in JSON at position 17 Uncaught SyntaxError: Unexpected token s in JSON at position 4 - Uncaught SyntaxError: Unexpected token s in JSON at position 4 错误-变得更大的JSON文件时出现意外令牌 - ERROR - unexpected token when getting bigger JSON file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM