如何修复 'form' 被赋值但从未在 axios 中使用

How to fix 'form' is assigned a value but never used in axios

我在本地主机上使用前端带有 axios 的 React 和后端带有 nodemailer 的 Express 的联系表单有问题。预期的结果是,当我单击 "Submit" 按钮时,我应该会收到电子邮件,但是当我单击它时,网站会刷新并且 URL 更改为: http://localhost:3000/?email=test%40gmail.com&message=fdsfd 如果我通过 test@gmail.comemail 字段中,但未收到电子邮件。

我的前端包含 App.tsx 文件(我使用 reactstrap 进行样式设置):

import React, { Component } from "react";
import { Button, Form, FormGroup, Label, Input } from "reactstrap";
import axios from "axios";

class App extends Component {
  state = {
    email: "",
    message: ""
  };

  handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({ email: e.target.value, message: e.target.value });
  };

  async handleSubmit(e: React.ChangeEvent<HTMLInputElement>) {
    e.preventDefault();
    const email = {
      email: this.state.email
    };

    const message = {
      message: this.state.message
    };

    const form = await axios.post("/api/form", {
      email,
      message
    });
  }

  render() {
    return (
      <>
        <div>
          <Form id="contact-form">
            <FormGroup onSubmit={this.handleSubmit} method="POST">
              <Label for="exampleEmail">Email</Label>
              <Input
                type="email"
                name="email"
                id="email"
                placeholder="with a placeholder"
                onChange={this.handleChange}
              />
            </FormGroup>
            <FormGroup>
              <Label for="exampleMessage">Message</Label>
              <Input
                type="textarea"
                name="message"
                id="message"
                placeholder="with a placeholder"
                onChange={this.handleChange}
              />
            </FormGroup>
            <Button type="submit">Submit</Button>
          </Form>
        </div>
      </>
    );
  }
}

export default App;

我的后端包含 index.ts 文件:

import express, { Application, Request, Response, NextFunction } from "express";
import bodyParser from "body-parser";
import nodemailer from "nodemailer";

const app: Application = express();

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

app.post("/api/form", (req: Request, res: Response) => {
  nodemailer.createTestAccount((err, account) => {
    const htmlEmail = `
    <h3>Contact details</h3>
    <ul>
        <li>Email: ${req.body.email}</li>
    </ul>
    <h3>Message</h3>
    <p>${req.body.message}</p>
     `;

    const transporter = nodemailer.createTransport({
      host: "smtp.ethereal.email",
      port: 587,
      auth: {
        user: "MY_TEST_EMAIL_NAME",
        pass: "MY_TEST_EMAIL_PASSWORD"
      }
    });
    const mailOptions = {
      from: "test@testaccount.com",
      to: "MY_TEST_EMAIL_NAME",
      replyTo: "test@testaccount.com",
      subject: "new message",
      text: req.body.message,
      html: htmlEmail
    };
    transporter.sendMail(mailOptions, (err, info) => {
      if (err) {
        return console.log(err);
      }
      console.log("message sent: %s =", info.message);
      console.log("message URL: %s =", nodemailer.getTestMessageUrl(info));
    });
  });
});

const PORT = 5000;

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

为了启动应用程序(后端和前端),我同时使用如下所示:

 "scripts": {
    "build": "tsc -p backend/.",
    "backend": "nodemon backend/dist/index.js",
    "frontend": "cd frontend && yarn start",
    "dev": "concurrently --kill-others-on-fail \"yarn backend\" \"yarn frontend\""
  },

应用程序启动后终端中的输出如下所示:

yarn run v1.17.3
$ concurrently --kill-others-on-fail "yarn backend" "yarn frontend"
$ nodemon backend/dist/index.js
$ cd frontend && yarn start
[0] [nodemon] 1.19.1
[0] [nodemon] to restart at any time, enter `rs`
[0] [nodemon] watching: *.*
[0] [nodemon] starting `node backend/dist/index.js`
$ react-scripts start
[0] Server listening on port 5000
[1] Starting the development server...
[1] 
[1] Compiled with warnings.
[1] 
[1] ./src/App.tsx
[1]   Line 25:  'form' is assigned a value but never used  @typescript-eslint/no-unused-vars
[1] 
[1] Search for the keywords to learn more about each warning.
[1] To ignore, add // eslint-disable-next-line to the line before.

单击"Submit"后可以更改什么以接收电子邮件?似乎从未使用过使用 axios 定义的表单,但我不知道如何修复它。这是我在 Whosebug 上的第一个 post。提前致谢。

只是一个warning,因为这一行,

const form = await axios.post("/api/form", {
      email,
      message
});

在这里您将 axios 调用的 return 分配给了 form 变量,但您从未使用过它。你只需要删除它,

await axios.post("/api/form", {
      email,
      message
});

或者您可以仅将其用于 console.log

const form = await axios.post("/api/form", {
      email,
      message
});

console.log(form); //check here