I created an API using express and I want to use it in my front-end server, the issue is that in order for my api to work I have to constantly run it on a server. However I can't do that simultaneously running my react application. So my question is how can I start my react server and api at the same time?
P.S. I tried out concurrently but I'm confused on how to get it working, heres some sample code from my package.json
{
"name": "app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.1.1",
"@material-ui/icons": "^4.2.0",
"axios": "^0.19.0",
"concurrently": "^4.1.0",
"express": "^4.17.1",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1"
},
"scripts": {
"start": "node src/connection",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"react": "react-scripts start",
"dev": "concurrently \"npm start\" \"npm react\""
},
"proxy": "http://localhost:3000",
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": []
}
}
In 5 steps:
npm i --s concurrently
package "client": "npm start --prefix client",
"clientinstall": "npm install --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client"
Install package npm-run-all, which helps you to execute multiple scripts. You can refer the below link:
https://www.npmjs.com/package/npm-run-all
After installing this package, In your package.json, add the script like this:
"scripts": {
"start-js": "react-scripts start",
"backend-start": "NODE_ENV=production node node_api/server.js",
"start": "concurrently \"npm-run-all -p backend-start start-js\"",
"build": "npm-run-all build-css && react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
Here, when you run the command "npm start", it first run the "backend-start" script which starts your backend server and then it starts react.
Just change the path in "backend-start" script. replace "node_api/server.js" with your path node startup file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With