0

我正在使用 http-proxy-middleware 将表单数据从 React 前端发送到 Express 服务器,
http-proxy-middleware似乎不起作用。
它应该代理到localhost://5000.
而是引发错误:

POST http://localhost:3000/api/sendMail 404(未找到)。

前端代码:

import React, { Component } from "react";
import axios from "axios";

class EmailForm extends Component {
  state = {
    name: "",
    email: ""
  };

  handleSubmit = async e => {
    e.preventDefault();
    const data = {
      name: this.state.name,
      email: this.state.email
    };
    console.log(data);

    axios.post("/api/sendMail", data);
  };

  handleChange = e => {
    this.setState({
      [e.target.id]: e.target.value
    });
  };

  render() {
    return (
      <div className="container mt-3">
        <form onSubmit={this.handleSubmit}>
          <h4 className="grey-text text-darken-3">Send Email</h4>
          <div className="form-group">
            <label htmlFor="email">Name</label>
            <input
              className="form-control"
              type="text"
              id="name"
              onChange={this.handleChange}
            />
          </div>
          <div className="form-group">
            <label htmlFor="email">Email</label>
            <input
              className="form-control"
              type="email"
              id="email"
              onChange={this.handleChange}
            />
          </div>
          <div className="form-group">
            <button className="btn btn-danger">SendMeEmail</button>
          </div>
        </form>
      </div>
    );
  }
}

export default EmailForm;

setupProxy.js:

const proxy = require("http-proxy-middleware");
module.exports = function(app) {
  app.use(proxy("/api", { target: "http://localhost:5000/" }));
};

服务器.js:

app.post("/api/sendMail", (req, res) => {
  console.log(req.body);
});
4

1 回答 1

0

将此行添加到 package.json (反应项目)

"proxy": "http://localhost:5000"
于 2021-01-27T19:01:28.617 回答