如何将react-final-form与后端连接

时间:2019-07-08 14:56:10

标签: reactjs express axios nodemailer react-final-form

以下是使用react-final-form创建的地雷形式:

import React from "react"
import { Form, Field } from "react-final-form"
import * as Yup from "yup"
import axios from "axios"

import Layout from "../components/layout"
import servisStyles from "./servis.module.sass"

const onSubmit = async values => {
  await axios.post("/send", { values }).then(console.log(values))
}

const Contact = ({ email, password, newsletter, plan }) => (
  <Layout>
    <Form
      onSubmit={onSubmit}
      initialValues={{
        email: email || "",
        password: password || "",
        newsletter: newsletter || true,
        plan: plan || "free",
      }}
      render={({ handleSubmit, submitting }) => (
        <form onSubmit={handleSubmit} className={servisStyles.form__control}>
          <Field
            name="email"
            validate={value => {
              try {
                Yup.string()
                  .required("Email is required")
                  .email("Email not valid")
                  .validateSync(value)
              } catch (err) {
                return err.errors[0]
              }
            }}
            render={({ input, meta }) => (
              <div>
                {meta.touched && meta.error && <p>{meta.error}</p>}
                <input {...input} type="email" placeholder="Email" />
              </div>
            )}
          />
          <Field
            name="password"
            validate={value => {
              try {
                Yup.string()
                  .required("Password is required")
                  .min(6, "Password must be 9 characters or longer")
                  .validateSync(value)
              } catch (err) {
                return err.errors[0]
              }
            }}
            render={({ input, meta }) => (
              <div>
                {meta.touched && meta.error && <p>{meta.error}</p>}
                <input {...input} type="password" placeholder="Password" />
              </div>
            )}
          />

          <div>
            <Field name="newsletter" type="checkbox" component="input" />
            <label> Join our newsletter </label>
          </div>

          <Field name="plan" component="select">
            <option value="free">Free</option>
            <option value="premium">Premium</option>
          </Field>

          <button type="submit" disabled={submitting}>
            Submit
          </button>
        </form>
      )}
    />
  </Layout>
)

export default Contact

...这是server.js文件的代码:

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

const app = express()

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

async function main() {
  const output = `
        <p>You have a new contact request</p>
        <h3>Contact Details</h3>
        <ul>  
          <li>Email: </li>
          <li>Password: </li>
          <li>Newsletter: </li>
          <li>Plan: </li>
        </ul>
        <h3>Message</h3>
        <p>Message goes here</p>
      `

  let transporter = nodemailer.createTransport({
    host: "smtp.mail.yahoo.com",
    port: 587,
    secure: false,
    auth: {
      user: "account_username_here",
      pass: "account_password_here",
  })

  // send mail with defined transport object
  let info = await transporter.sendMail({
    from: "Test Name <test@test.com>", // sender address
    to: "receiver@email.com", // list of receivers
    subject: "Message Subject", // Subject line
    html: output, // html body
  })

  console.log("Message sent: %s", info.messageId)
}
main().catch(console.error)

当我运行联系表单并按提交按钮时,将发送按钮值,我可以在控制台中看到它们。

当我运行server.js时,它可以工作并将消息发送到我的电子邮件中。

问题是我不知道如何连接这2个文件并创建有效的联系表。

请帮助。

我试图将nodemailer代码包装在其中

app.post('/send', values => {
    async function main() {
    ....
    }
})

但这不起作用。

编辑: 现在我有新问题。 联系人表单正在运行,并且已发送消息,但一段时间后出现错误:

BadRequestError: request aborted
[0]     at IncomingMessage.onAborted (/Users/denis/Desktop/gatsby/node_modules/body-parser/node_modules/raw-body/index.js:231:10)
[0]     at IncomingMessage.emit (events.js:182:13)
[0]     at abortIncoming (_http_server.js:444:9)
[0]     at socketOnClose (_http_server.js:437:3)
[0]     at Socket.emit (events.js:187:15)
[0]     at TCP._handle.close (net.js:599:12)
[0] BadRequestError: request aborted
[0]     at IncomingMessage.onAborted (/Users/denis/Desktop/gatsby/node_modules/body-parser/node_modules/raw-body/index.js:231:10)
[0]     at IncomingMessage.emit (events.js:182:13)
[0]     at abortIncoming (_http_server.js:444:9)
[0]     at socketOnClose (_http_server.js:437:3)
[0]     at Socket.emit (events.js:187:15)
[0]     at TCP._handle.close (net.js:599:12)
error Error when trying to proxy request "/api/send" to "http://localhost:3000/api/send"

[1] 
[1]   RequestError: socket hang up
[1]   
[1]   - index.js:220 ClientRequest.req.once.err
[1]     [gatsby]/[got]/index.js:220:22
[1]   
[1]   - next_tick.js:63 process._tickCallback
[1]     internal/process/next_tick.js:63:19

1 个答案:

答案 0 :(得分:0)

我在Reactjs上使用代理,除了两个文件都在同一目录中 我在package.json中添加如下代码:

{
  "name": "xxx",
  "dependencies": {
  "xxxx":"xxx,"
  "...":".."
  },
  "scripts": {
  "start": "react-scripts start",
  },
  "proxy": "http://localhost:5000/"
}
服务器

中开发人员的5000端口

您还可以调整配置

export const URL= process.env.NODE_ENV === 'production' 
  ? 'http://xxx.xxx.xxx'
  : 'http://localhost:5000'