0

I am using http-proxy-middleware to send my form data from React front end to Express server,
but http-proxy-middleware doesn't seem to work.
It should proxy to localhost://5000.
Instead throws an error:

POST http://localhost:3000/api/sendMail 404 (Not Found) .

front end code:

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);
});
SherylHohman
  • 16,580
  • 17
  • 88
  • 94

1 Answers1

0

Add this line to package.json (of react project)

"proxy": "http://localhost:5000"
Eric Aya
  • 69,473
  • 35
  • 181
  • 253