6

Actually, I am looking to create the contact form in the website using reactjs and nodejs. I have created the form using the React and for the backend, I have to connect the node js so that I can receive the email. But it is not happening Both React and Node should run on the same port. I have given a proxy as "http://localhost:3000" in the package.json but still, it's not working.

I have given both the react js and node js code. Please help me to solve this error.

React JS Code

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

export default class formSection extends Component {
  state = {
    name: "",
    email: "",
    subject: "",
    comment: ""
  };

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

 async handleSubmit(e) {
    e.preventDefault()
    const {name, email, subject, comment} = this.state

    const contact = await axios.post('/api/contact', {

        name,
        email,
        subject,
        comment

    })

  };

  render() {
    return (
      <section
        className="wow fadeIn big-section"
        id="section-down"
        style={{ visibility: true }}
      >
        <div className="container">
          <div className="row equalize sm-equalize-auto">
            <div
              className="col-md-6 col-sm-12 col-xs-12 sm-margin-30px-bottom wow fadeInLeft"
              style={{ visibility: true, height: 597 }}
            >
              <div className="padding-fifteen-all bg-light-gray border-radius-6 md-padding-seven-all xs-padding-30px-all height-100">
                <span className="text-extra-dark-gray alt-font text-large font-weight-600 margin-25px-bottom display-block">
                  Ready to get started?
                </span>
                <form id="contact-form" onSubmit={e=>this.handleSubmit(e)} method="POST">
                  <div>
                    <div
                      id="success-contact-form"
                      className="no-margin-lr"
                      style={{ display: true }}
                    />
                    <input
                      type="text"
                      name="name"
                      id="name"
                      value={this.state.name}
                      placeholder="Name*"
                      className="border-radius-4  medium-input"
                      onChange={this.handleChange}
                    />
                    <input
                      type="text"
                      name="email"
                      value={this.state.email}
                      id="email"
                      placeholder="E-mail*"
                      className="border-radius-4  medium-input"
                      onChange={this.handleChange}
                    />
                    <input
                      type="text"
                      name="subject"
                      id="subject"
                      value={this.state.subject}
                      placeholder="Subject"
                      className="border-radius-4  medium-input"
                      onChange={this.handleChange}
                    />
                    <textarea
                      name="comment"
                      id="comment"
                      value={this.state.comment}
                      placeholder="Your Message"
                      rows="5"
                      className="border-radius-4  medium-textarea"
                      onChange={this.handleChange}
                    />
                    <button
                      id="contact-us-button"
                      type="submit"
                      className="btn btn-small border-radius-4 btn-dark-gray"

                    >
                      send message
                    </button>
                  </div>
                </form>
              </div>
            </div>
            <div
              className="col-md-6 col-sm-12 col-xs-12 last-paragraph-no-margin wow fadeInRight"
              style={{ visibility: true, height: 597 }}
            >
              <div className="padding-ten-all bg-light-gray border-radius-6 md-padding-seven-all xs-padding-30px-all height-100 sm-text-center">
                <img
                  src="images/about-img1.jpg"
                  alt=""
                  className="border-radius-6 margin-35px-bottom xs-margin-30px-bottom"
                  data-no-retina=""
                />
                <span className="text-large font-weight-600 alt-font text-extra-dark-gray margin-5px-bottom display-block">
                  Let's plan for a new project?
                </span>
                <p>
                  Lorem Ipsum is simply dummy text of the printing and
                  typesetting industry, Lorem Ipsum has been the standard dummy
                  text.
                </p>
                <a
                  href="about-us-modern.html"
                  className="btn btn-dark-gray btn-small text-extra-small border-radius-4 margin-25px-top"
                >
                  About Company
                </a>
              </div>
            </div>
          </div>
        </div>
      </section>
    );
  }
}

Node JS Code

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const app = express();

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

app.post('/api/contact', (req, res) => {

console.log(req.body);

});




const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {

    console.log(`server listening in port ${PORT}`);

})
7
  • want you run react and node on equal port? Commented Oct 31, 2018 at 13:16
  • Yeah on Port 3000! I tried but not working. Could you please help? Commented Oct 31, 2018 at 13:19
  • 1
    React doesn't run on its own port. It runs on Node, which runs on port 3000. It's not clear what your problem is. In what way is it "not working"? Where are you injecting React into your index page? Commented Oct 31, 2018 at 13:22
  • 1
    you can do this JUST when use one nodejs server for react SSR and API sever. this is mean you can not use tools like create-react-app. are you use tools or pure react? Commented Oct 31, 2018 at 13:24
  • @mihai Created the form using React(i.e)Front End. Now have to send email using node js server. If I start the node server, the front end is not working. Please check the code above. Commented Oct 31, 2018 at 13:30

6 Answers 6

7

You can't achieve this with the approach you are following.

why?

you are trying to run two different servers at a single port (node server and webpackdev server)

Any alternative?

yes, as per your requirement you don't need a separate server for the frontend, you can serve it as static files.

How?

  1. build your application (for create-react-app npm run build)

  2. copy all the contents of build folder to a new folder (say public) in your express application.

  3. now add below in your node js code (to serve static files):

    app.use('/', express.static('./public'));

and now visit http://localhost:3000

Sign up to request clarification or add additional context in comments.

3 Comments

any downside for this? pros and cons? it works for me. It is safe in production?
i think in production you need to specify in package.json to build the react-app than copy the content from build to public folder,maybe using github action you can achieve this
How to handle reshresh case on this. Say I have an endpoint /schema and I typed this in browser and refresh. But this endpoint will hit back end (node) and error will be thrown as Cannot GET /schema. How to redirect to public folder if the endpoint is not present in API.
4

I assume you're using create-react-app, and you've added proxy configuration to package.json.

Create-react-app is started on 3000 port, so your express server should start on any other port (NOT 3000), then you change the proxy configuration to that port.

I.e. const PORT = process.env.PORT || 5000; Than change frontend package.json proxy configuration like "proxy": "http://localhost:5000"

Notice, that this should be used for development only. For production: build the bundle, and use express to serve static contents from build folder.

8 Comments

I did accordingly but getting an error as "Cannot GET /"
@Ameen check the log of the server process. does it states "server listening in port 5000"? I'm asking, since I've just made all of these steps, and everything works fine.
@Ameen, wait, how are you checking that?
yeah got the same status message as "server listening in port 5000". No error in that
Using visual studio code editor, there it shows the status and using nodemon as well to restart the server
|
3

if you use tools like create-react-app answer is 'can not do this', because you cannot edit nodejs server and in other side in production mode, create-react-app build project and have not any nodejs server in production.

but when you develop react as pure and SSR then you can access to nodejs server and can do this.

see this for react SSR:

https://medium.freecodecamp.org/demystifying-reacts-server-side-render-de335d408fe4

1 Comment

Someone marked a question I posted as possible duplicate. Not sure if it applies, since my goal would be to run 2 scripts (separate files) in one port. Is that possible? stackoverflow.com/questions/62155391/…
1

Solution if you use webpack/dev-server

package.json file:

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

If you use dev-sever with webpack, then in webpack.cofing.js add this:

    proxy: {
        '/api': "http://localhost:5000",
    },

backend.js file:

const server = http.createServer((req, res) => {
  res.write('Hello World!');
  res.end();
});

server.listen({
  host: 'localhost',
  port: 5000,
});

When you open site type: localhost:8080 (or which is default for you), and then when you want to open your node.js server just add /api in your url it should look like this: localhost:8080/api.

Comments

0

I have found the solution How to start react and nodejs app on the same port. please open git link https://github.com/chandrakant1990/react-node-express-app-on-same-port

Take a clone of this repo. In Client forlder just fire command npm install then start the app sh start.sh

Your app will be started on localhost:3000

For Client side changes You need not to restart the app again. For server side changes please restart the app.

For more details you can see video https://youtu.be/AiEC2_8mIIY

Comments

0

The only way I see is best to achieve using the same port is to use server-side rendering. you can learn more about this here

https://www.freecodecamp.org/news/demystifying-reacts-server-side-render-de335d408fe4/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.