Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the same port for React Js and Node Js?

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}`);

})
like image 729
Ameen Avatar asked Oct 31 '18 12:10

Ameen


People also ask

Can React and node be on same port?

Neither react nor node use any network ports as they have no networking capabilities themselfs. It's the web server (e.g. express js) which uses node as the runtime environment or the database server that use ports. You can serve your assets (react app, html, css) from the same web server.

Can you use React and Nodejs together?

With the combination of Node and React, developers don't require learning complex back-end languages like Python or Ruby. They can use Node for server-side development and React for front-end code building without switching between frameworks and programming languages. And it saves resources, money, and time.

Can you run backend and frontend on same port?

You'd want to somehow combine both servers, so they can interact with each other. But each can only run on its own port. You can't start both on the same one and if they are apart, it's impossible for the frontend code to access the backend endpoints.


2 Answers

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

like image 82
Rohit Sharma Avatar answered Sep 27 '22 22:09

Rohit Sharma


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.

like image 29
Sim Dim Avatar answered Sep 27 '22 21:09

Sim Dim