【问题标题】:How to connect react-final-form with backend如何将 react-final-form 与后端连接
【发布时间】:2019-11-18 03:03:24
【问题描述】:

这是我用 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 时,它会工作并将消息发送到我的电子邮件。

问题是我不知道如何连接这两个文件并制作有效的联系表单。

请帮忙。

我尝试将 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

【问题讨论】:

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


    【解决方案1】:

    我在 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'

    【讨论】:

    • 我的应用程序在 8000 端口运行。我确实尝试在 package,json 中添加代理并将其设置为 3000 但它不起作用。
    • 顺便说一句,这是一个 gatsby 应用程序
    • gastby,你已经用过thatHere
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    相关资源
    最近更新 更多