React Axios Post 回调问题

React Axios Post Callback Trouble

我在使用 axios.post 获得回调以使用 nodeMailer 发送邮件时遇到了很大的困难。你看,电子邮件已发送,但它实际上根本不打印任何控制台日志。

这是我的代码:

 handleSubmit = async(e) => {
        e.preventDefault();

        const { email, fullname, number, subject, message } = this.state;


            await axios.post('/api/form', {
                email,
                fullname,
                number,
                subject,
                message
              })
              .then((info)=> {
                this.setState({email: '', fullName: '', subject: '', message: ''});
                Alert.success('Success.', {
                    position: 'top-right',
                    effect: 'jelly',
                    timeout: 4000
                });
                console.log(response);
              })
              .catch((e)=> {
                console.log(error);
              });
    }

这是服务器中的其他代码 (index.js):

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

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use((request, response, next) => {
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Allow-Headers", "Content-Type");
    next();
  });

if (process.env.NODE_ENV === 'production') {
    app.use(express.static('client/build'));

    const path = require('path');
    app.get('*', (req, res) => {
      res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
    });
  }

app.post('/api/form', (req, res) => {

    let transporter = nodemailer.createTransport({
        host: 'host',
        port: 465,
        secure: true, // true for 465, false for other ports
        auth: {
            user: '', // generated ethereal user
            pass: '' // generated ethereal password
        }
    });

    let mailOptions = {
        from: '"New message "<>', // sender address
        to: 'me', // list of receivers
        subject: 'New message', // Subject line
        html: 'Content here' // plain text body// html body
    };

    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);
        // Preview only available when sending through an Ethereal account
        console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));

        // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>
        // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
    });

});


const PORT = process.env.PORT || 3001;

app.listen(PORT, () => {
    console.log('Server running on port 3001.')
})

这里似乎有什么问题?我试过使用 'axios.get' 和 'axios.request',这至少会输出一个错误。

我用了一个Promise等待传输器的响应发送到前端被axios

解析
const sendMail = () => new Promise((resolve, reject) => {
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      reject(error);
    } else {
      resolve(info);
    }
  });
})
.....other code.....
const status = await sendMail();
res.json({status})

LE

根据您的代码,/api/form 路由应该是这样的

app.post('/api/form', async (req, res) => {

  const transporter = nodemailer.createTransport({
    host: 'host',
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
      user: '', // generated ethereal user
      pass: '' // generated ethereal password
    },
  });

  const mailOptions = {
    from: '"New message "<>', // sender address
    to: 'me', // list of receivers
    subject: 'New message', // Subject line
    html: 'Content here' // plain text body// html body
  };

  const sendMail = () => new Promise((resolve, reject) => {
    transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
        reject(error.message);
      } else {
        resolve(`Message sent: ${info.messageId}`);
      }
    });
  });

  const status = await sendMail();
  res.json({ status });

});