【问题标题】:Send email with React, Redux Form, Nodemailer and Express使用 React、Redux Form、Nodemailer 和 Express 发送电子邮件
【发布时间】:2019-03-13 11:54:06
【问题描述】:

我一直试图弄清楚如何在提交 Redux 表单后发送电子邮件。经过几天寻找合适的解决方案,我合并了其中的一些,这就是结果。

客户端:

这是我的联系表格的组成部分:

import React from 'react'
import { Field, reduxForm } from 'redux-form'

class Info extends React.Component {
    renderError({ error, touched }) {
        if (touched && error) {
            return <div>{error}</div>
        }
    }

    renderInputField = ({ input, label, meta }) => {
        return (
            <div>
                <input {...input} type="text" placeholder={label} />
                {this.renderError(meta)}
            </div>
        );
    };

    onSubmit = (formValues) => {
        this.props.onSubmit(formValues)
    }

    render() {
        const { handleSubmit, pristine, submitting } = this.props
        return (
            <div>
                <form onSubmit={handleSubmit(this.onSubmit)}>
                    <div>
                        <Field
                            name="nome"
                            component={this.renderInputField}
                            label="Nome *"
                        />
                    </div>
                    <div>
                        <Field
                            name="cognome"
                            component={this.renderInputField}
                            label="Cognome *"
                        />
                    </div>
                    <div>
                        <Field
                            name="email"
                            component={this.renderInputField}
                            label="Email *"
                        />
                    </div>
                    <div>
                        <Field
                            name="azienda"
                            component={this.renderInputField}
                            label="Azienda"
                        />
                    </div>
                    <div>
                        <Field
                            name="citta"
                            component={this.renderInputField}
                            label="Città / CAP / Provincia"
                        />
                    </div>
                    <button type="submit" disabled={pristine || submitting}>Visualizza</button>
                </form>
            </div>
        )
    }
}

const validate = formValues => {
    const errors = {}

    if (!formValues.nome) {
        errors.nome = "Aggiungi il nome"
    }

    if (!formValues.cognome) {
        errors.cognome = "Aggiungi il cognome"
    }

    if (!formValues.email) {
        errors.email = "Aggiungi l'email"
    } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(formValues.email)) {
        errors.email = 'Email non valida'
    }

    return errors
}

export default reduxForm({
    form: 'companyData',
    destroyOnUnmount: false,
    forceUnregisterOnUnmount: true,
    validate
})(Info)

这是使用联系表单的组件(父组件),我使用 axios 将数据发送到在端口 3001 上运行的服务器。 重要的部分是 handleFormSubmit 方法:

import React from 'react'
import Data from '../components/form/Data'
import Calculation from '../components/form/Calculation'
import Info from '../components/form/Info'
import Details from '../components/form/Details'
import axios from 'axios'

class WizardForm extends React.Component {
    constructor(props) {
        super(props)
        this.nextPage = this.nextPage.bind(this)
        this.previousPage = this.previousPage.bind(this)
        this.handleFormSubmit = this.handleFormSubmit.bind(this)
        this.state = {
            page: 1,
        }
    }
    nextPage() {
        this.setState({ page: this.state.page + 1 })
    }

    previousPage() {
        this.setState({ page: this.state.page - 1 })
    }

    async handleFormSubmit(formValues) {
        const name = formValues.nome
        const surname = formValues.cognome
        const email = formValues.email
        const response = await axios.post('http://localhost:3001/send', {
            name: name,
            surname: surname,
            email: email,
        })
        console.log(response)
    }


    render() {
        const { page } = this.state
        return (
            <div>
                {page === 1 && <Data onSubmit={this.nextPage} />}
                {page === 2 && (
                    <Calculation
                        previousPage={this.previousPage}
                        nextPage={this.nextPage}
                    />
                )}
                {page === 3 && (
                    <Info
                        onSubmit={this.handleFormSubmit}
                    />
                )}
                {page === 4 && (
                    <div>
                        <Details />
                    </div>
                )}
            </div>
        )
    }
}

export default WizardForm

服务器端:

这是我的 app.js 文件,使用命令“node app.js”运行:

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

const app = express();


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


app.use(cors());


app.post('/send', (req, res) => {
    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
        host: 'ssl0.ovh.net',
        secure: true,
        port: 465,
        auth: {
            user: 'matteo.schiatti@abstract-technology.com',
            pass: 'g6vqUImUzJX_cw',
        },
        tls: {
            rejectUnauthorized: false,
        }
    });

    let name = req.body.name
    let surname = req.body.surname
    let email = req.body.email
    let content = `name: ${name} \n surname: ${surname} \n email: ${email} `

    // setup email data with unicode symbols
    let mailOptions = {
        from: '"John" <matteo.schiatti@abstract-technology.com>', // sender address
        to: 'matteo.schiatti@gmail.com', // list of receivers
        subject: 'This is a test', // Subject line
        text: content, // plain text body
    };

    // send mail with defined transport object
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);
    });
});


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


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

app.listen(PORT, () => {
    console.log(`App listening on port ${PORT}!`);
});

完成所有这些后,电子邮件已发送,但我遇到了一些问题:

1 - 我无法获取 console.log(response),控制台中没有任何内容,邮件已发送但 axios 没有给我回复。我试图搜索一些东西,这里说问题是 event.preventDefault():

Axios post doesn't receive answer (ReactJS)

但是Redux Form的handleSubmit已经使用了preventDefault,我也尝试过使用event.preventDefault()而不是handleSubmit但是什么也没用。 我真的需要找到获得响应的方法,因为当我得到肯定的结果时,我需要更改“页面”状态。任何的想法?

2- 电子邮件已发送,但如果我之后不重新加载页面(我需要不重新加载页面,因为我需要存储在 Redux 中的表单数据)我会收到一封双封电子邮件,所以几分钟后另一个相同的电子邮件被发送。

找到解决方案真的很困难,因为我必须合并不同的指南来找出一些东西,希望我能做到这一点,这样我就可以为想要构建类似东西的人创建一个清晰的分步指南。

希望我把所有的信息都放进去

【问题讨论】:

    标签: reactjs express axios redux-form nodemailer


    【解决方案1】:

    1.

       async handleFormSubmit(formValues) {
            const name = formValues.nome
            const surname = formValues.cognome
            const email = formValues.email
            const response = await axios.post('http://localhost:3001/send', {
                name: name,
                surname: surname,
                email: email,
            }).then((response)=> console.log(response)
        }
    

    当状态为 200 以及状态不同时,您可以在 express.js 中通过 API 发送响应。 当你触发时,你可以这样做。

      function = () => {
        const { saveValue } = this.props;
         this is a async action.
        saveValues().then(() => {
          console.log('Success');
        }).catch(() => {
          console.log('Error');
        });
      };
    

    2.Redux 表单已经使用了 preventDefault 所以你不需要调用它。我认为你的 redux 表单代码有问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-27
      • 2018-07-14
      • 2015-05-19
      • 1970-01-01
      相关资源
      最近更新 更多