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

时间:2020-01-27 02:37:17

标签: node.js reactjs express http-proxy-middleware

我正在使用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/" }));
};

Server.js:

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

1 个答案:

答案 0 :(得分:0)

将此行添加到 package.json(来自 react 项目)

"proxy": "http://localhost:5000"