最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use the same port for React Js and Node Js? - Stack Overflow

programmeradmin2浏览0评论

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

})

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

})
Share Improve this question asked Oct 31, 2018 at 12:49 AmeenAmeen 911 gold badge1 silver badge5 bronze badges 7
  • want you run react and node on equal port? – Mohmmad Ebrahimi Aval Commented Oct 31, 2018 at 13:16
  • Yeah on Port 3000! I tried but not working. Could you please help? – Ameen 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? – jmargolisvt 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? – Mohmmad Ebrahimi Aval 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. – Ameen Commented Oct 31, 2018 at 13:30
 |  Show 2 more comments

6 Answers 6

Reset to default 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

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.

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

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.

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

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/

发布评论

评论列表(0)

  1. 暂无评论