Экспресс-запрос тело пусто в контактной форме - PullRequest
0 голосов
/ 15 мая 2018

Я использую nodemailer, чтобы добиться отправки писем из контактной формы. Мой app.js выглядит так

    app.post('/jobs/join-us', (req, res) => {
  console.log(req.body); //to return body
  const output = `


      <p>You have a new message from contact form.</p>
      <h3>Contact Details</h3>
      <ul> 
        <li>Name: ${req.body.name}</li>
        <li>Email: ${req.body.email}</li>
      </ul>
      <h3>Message</h3>
      <p>${req.body.message}</p>
    `;
  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    host: 'smtp.gmail.com',
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
      user: 'xx', // generated ethereal user
      pass: 'xx',
    },
    tls: {
      rejectUnauthorized: false
    }
  });

  // setup email data with unicode symbols
  let mailOptions = {
    from: 'xx', // sender address
    to: 'xx', // list of receivers
    subject: 'Contact Request', // Subject line
    text: 'Hello world?', // plain text body
    html: output // html body
  };

  // send mail with defined transport object
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      console.log(error);
      res.end("error");
    } else {
      console.log('Message sent: %s', info.messageId);
      //console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
      res.sendStatus(200);
    }
  });
});

Кто-нибудь может мне помочь? Я также пробую что-то вроде console.log (req) перед выводом const, но это не вернуло мне ничего жизнеспособного.

Это моя контактная форма, запрос POST возвращает 200.

       <div class='input-wrapper'>
<input class="flying-label-input" type="text" name="job_form[role]" id="job_form_role" />
<label class="flying-label required" for="job_form_role">Role</label>
</div>
<div class='input-wrapper'>
<input class="flying-label-input" type="text" name="job_form[email]" id="job_form_email" />
<label class="flying-label required" for="job_form_email">E-mail</label>
</div>
<div class='input-wrapper'>
<input class="flying-label-input" type="text" name="job_form[phone_number]" id="job_form_phone_number" />
<label class="flying-label" for="job_form_phone_number">Phone number</label>
</div>
<div class='input-wrapper'>
<label class="label required" for="job_form_cv">CV (PDF)</label>
<input type="file" name="job_form[cv]" id="job_form_cv" />
</div>

<div class='input-wrapper-space-top'>
<input type="hidden" name="job_form[referer]" id="job_form_referer" />
<input type="submit" name="commit" value="Submit Job Application" class="btn-round btn-primary" />
</div>

Функции промежуточного ПО моего app.js: '

const express = require('express')
var app = express();
var path = require('path')
const nodemon = require('nodemon')
const nodemailer = require('nodemailer');
const bodyParser = require('body-parser');

// Static folder
app.use(express.static('public'))

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json())

1 Ответ

0 голосов
/ 15 мая 2018

req.body по умолчанию undefined, поэтому тот факт, что вы получаете пустой объект, означает, что вы не заполняете req.body body-parser и / или multer. Это также подтверждается тем фактом, что перехват if statement не возвращает ошибку в консоли, поэтому req.body находится там, и это пустой объект. Попробуйте следующее промежуточное программное обеспечение перед вашим app.post и обновите app.post следующим образом:

var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data

app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/jobs/join-us', upload.array(), function (req, res, next) {
  console.log(req.body);
  res.json(req.body);
});
...