1

I have a normal React App which runs on Node Server

-node_modules
-src
   -Actions
   -Components
   -Stores
   -Server
     -server.js
-package.json   

Basically when i run npm start React App will run and for suppose i will be able to see the example in localhost:8080

Now my server.js file includes MySql code

var mysql = require('mysql');

var con = mysql.createConnection({
    host: "localhost",
    user: "yourusername",
    password: "yourpassword"
});

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
});

I have to explicitly run node server.js command to get the connection to mysql and run the queries their.

How do i integrate server.js command in my React App, so that when i run npm start, my MySql connection and the file should execute

4
  • With npm start, you might be using webpack-dev-server then, am I right? Commented May 25, 2018 at 6:34
  • So then change the start script in package.json to "start": "NODE_PATH=$NODE_PATH:./src node server",. That will call your node server and it will work then. Commented May 25, 2018 at 6:37
  • you can add node server in your npm scripts using && operator like this "scripts": { "start": "webpack-dev-server --config './webpack/webpack.config.js' && node server" } Commented May 25, 2018 at 6:38
  • Possible duplicate of stackoverflow.com/questions/38817917/… Commented May 25, 2018 at 6:39

1 Answer 1

2

The short answer is: you don't.
The short fix is: use some kind of program to help you start both (like npm)

The long answer is:

Set up your npm start task to run both of them. You can do this with concurrently. (npm install --save concurrently)

Change your npm start task (in your package.json) to something like this:

"start": "concurrently -k -r -s first \"node server.js\" \"webpack-dev-server""

If you need further assistance please share your package.json file.

The longest answer is:

This part is OPTIONAL, only follow it if you want to LEARN.

If you want more details you could look at a somewhat more advanced project such as my react-sane-starter to get an idea how to efficiently start multiple services. This project also contains Docker if you're interested.

concurrently over &

People often suggest to run one of the tasks in the background using &, this will usually prevent logs being shown (unless redirected), I'd highly recommend using concurrently to solve this issue. (it will prefix your different services quite nicely)

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

2 Comments

Thanks for taking your time for explaining these things.
No problem, enjoy!

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.