0
votes

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);
});
1
You're using React right? Your react run on port: 3000 right and than, your express server run on port??? - Titus Sutio Fanpula
server on port 5000 and I am using concurrently - Kartik Gupta
If your server running on port 5000, than why you're using 3000 here: http://localhost:3000/api/sendMail? I'ts must using 5000, then it's will looks like this: ` localhost:5000/api/sendMail ` - Titus Sutio Fanpula

1 Answers

0
votes

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

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