0

I'mt trying to send formData from my web app to the Express backend and send email with nodemailer as well. Mail transport works fine, except the req.body is getting empty, and the mail goes with a lot of "undefiend" fields as there must be data from the req.body.

Client side code:

async function formSend(e) {
    e.preventDefault();
  let formData = new FormData(form);
 try {
            const res = await fetch('/myendpoint', {
                method: 'Post',
                body: formData,
                Headers: {
                    'Content-type': 'application/json'
                }
            });
            if (res.ok) {
                const result = await res.json();
             }
               catch (error) {
            alert('error')
        }
      }
      };

Backend: Route:

router.post('/', (req, res) => {
console.log(req.body);
const { value1, value2, value3, value4, value5, value6, value7, value8} = req.body;

const output = `
<p>You have a new contact request</p>
<h3>Contact Details</h3>
<ul>  
  <li>Name: ${name}</li>
  <li>Email: ${email}</li>
  <li>Phone: ${phone}</li>
  <li>Category: ${category}</li>
  <li>status: ${status}</li>
  <li>Date: ${date}</li>
  <li>witness: ${witness}</li>
</ul>
<h3>Message</h3>
<p>${message}</p>
        `;


const transporter = nodemailer.createTransport({
    host: 'my mail server',
    port: 465,
    auth: {
        user: 'my mail',
        pass: 'my pass'
    }
});

const mailOptions = {
    from: req.body.email,
    to: 'my mail',
    subject: `Message from ${req.body.email}`,
    text: 'some title',
    html: output
};

transporter.sendMail(mailOptions, (err, info) => {
    if (err) {
        console.log(err);
        res.send('error');
    } else {
        console.log('Email sent' + info.response);
        res.status(200).json({ message: 'Email was sent' });
    }
});
});

     module.exports = router;

Server.js:

const express = require('express');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(express.json());


app.use('/api/contact', require('./routes/contact'));

The console.log of req.body and mail sent function

  {}
 Email sent250 OK id=1mopNr-006l01-Lh

While i'm trying to console.log formData values, it shows fine, i can see, that it is not empty, but after sending it to backend, it dissapears. May be there is a mistake with promises and async/await, can't realy understand it.

Vahe
  • 99
  • 1
  • 3
  • 12
  • What do you get when you dump your request headers? – SmileIT Nov 21 '21 at 16:32
  • This is request header. I tried to make request with Postman and it worked fine, but from the actual something goes wrong. POST /api/contact HTTP/1.1 Host: localhost:5000 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0 Accept: */* Accept-Language: en-GB,ru;q=0.7,hy;q=0.3 Accept-Encoding: gzip, deflate Referer: http://localhost:3000/ Content-type: application/json Origin: http://localhost:3000 Content-Length: 2 Connection: keep-alive Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: cross-site – Vahe Nov 21 '21 at 16:48
  • I'm wondering if the `FormData` object you're using is actually producing JSON that your server expects? Or does it make `application/x-www-form-urlencoded` by default and you don't have middleware on your server that reads that. – jfriend00 Nov 21 '21 at 17:01
  • Try encoding your body data as JSON before sending it over. I believe you have to use multipart content-type if you are using FormData object. – SmileIT Nov 21 '21 at 17:02
  • It seems i fount the solution here https://stackoverflow.com/a/55874235/13223597. All this time i was converting formData to JSON in some weird way that it does'nt work, but now it works ;) Thank you all for the comments. JSON.stringify(Object.fromEntries(formData)) – Vahe Nov 21 '21 at 17:12

0 Answers0