I have created a small React Express app and am struggling with deploying it to Heroku.
So far I have organised the client and server into separate folders.
Previously I had the contents of server in the projects root and client as its own folder accessed with a path.join however this didn't serve any of the build files so I opted to separate the folders.
Now with two folders I use a root package.json to install all dependencies and get both sides running.
{
"name": "project",
"version": "1.0.0",
"main": "",
"scripts": {
"start": "npm start --prefix server",
"install-client": "cd client && npm install && npm run build && cd ..",
"install-server": "cd server && npm install && cd .. ",
"heroku-postbuild": "npm run install-client && npm run install-server"
}
}
This works with my other folders in serving the back-end however there is no front-end at all. I'm wondering if there is a solution to this problem specifically or even a better way to deploy a full stack project in the same dyno.
This is my currently result on my Heroku app:
Heroku app result
And here any additional relevant files:
Main server file
const express = require('express');
const path = require('path');
const cors = require('cors');
const db = require('./config/db');
const app = express();
const PORT = process.env.PORT || 8080;
//Dependencies
app.use(express.json());
app.use(cors());
//Select all rows from table
app.get('/api/get', (req, res) => {
const selectAll = 'SELECT * FROM plant_data';
db.query(selectAll, (err, rows) => {
if (err) throw err;
res.send(rows);
});
});
//Insert into database
app.post('/api/insert', (req, res) => {
const row = req.body.row;
const insert = "INSERT INTO plant_data (test) VALUES (?)";
db.query(insert, [row], (err, rows) => {
if (err) throw err;
console.log("inserted: " + row);
});
});
//Server port
app.listen(process.env.PORT || PORT, () => {
console.log('Server started on port ' + PORT);
});
Main client file
import React, {useState, useEffect} from "react";
import axios from "axios";
export default function Index() {
const [data, setData] = useState('');
const [rows, setRows] = useState([]);
useEffect(() => {
axios.get('/api/get')
.then(res => {
setRows(res.data);
}).catch(err => {
console.log(err);
});
});
//Connects front-end submit to backend db
const insertRow = () => {
axios.post('/api/insert', {
row: data
});
};
return (
<>
<h1>Body</h1>
<input type="text" onChange={(e) => {
setData(e.target.value);
}} />
<button onClick={insertRow}>Submit</button>
{rows.map((row) => {
return <p>{row.test}</p>
})}
</>
);
};
Server package file:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"heroku-postbuild": "npm install --prefix client && npm run build --prefix client"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.0",
"cors": "^2.8.5",
"express": "^4.18.1",
"mysql": "^2.18.1",
"nodemon": "^2.0.19"
}
}
Client package file:
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.8.2",
"#material-ui/core": "^4.12.3",
"#mui/material": "^5.5.3",
"#testing-library/jest-dom": "^5.16.2",
"#testing-library/react": "^12.1.4",
"#testing-library/user-event": "^13.5.0",
"axios": "^0.27.2",
"hamburger-react": "^2.4.1",
"node-sass": "^7.0.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-helmet": "^6.1.0",
"react-router-dom": "^6.2.2",
"react-scripts": "5.0.0",
"styled-components": "^5.3.5",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Related
Here is my package.js file
{
"name": "cabed",
"version": "0.1.0",
"private": false,
"dependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"axios": "^0.27.2",
"electron-forge": "^5.2.4",
"electron-is-dev": "^2.0.0",
"electron-packager": "^17.1.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"main": "public/electron.js",
"homepage": "./",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"dev": "concurrently -k \"cross-env BROWSER=none npm start\" \"npm:electron\"",
"electron": "wait-on tcp:3000 && electron .",
"eb": "electron-packager C:/Users/user/cabed cddf --platform=win32 --arch=x64"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"concurrently": "^7.6.0",
"cross-env": "^7.0.3",
"electron": "^22.1.0",
"wait-on": "^7.0.1"
},
"config": {
"forge": {
"packagerConfig": {},
"makers": [
{
"name": "#electron-forge/maker-squirrel",
"config": {
"name": "stock_trading_app"
}
},
{
"name": "#electron-forge/maker-zip",
"platforms": [
"darwin",
"linux",
"win32"
]
},
{
"name": "#electron-forge/maker-deb",
"config": {}
},
{
"name": "#electron-forge/maker-rpm",
"config": {}
}
]
}
}
}
The generated exe with electron builder which i ran with
npm run eb
the exe generated by code above
does not render the react app inside the opened windows app.
Here is my app js
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div style={{justifyContent:'center',alignContent:'center',alignItems:'center'}}>
<div className="App">
<img src={logo} className="App-logo" alt="logo" />
<p>
Sasdsad
</p>
<p>
Sasdsad
</p>
</div></div>
);
}
export default App;
my electron.js looks like this under public directory.
const path = require('path');
const { app, BrowserWindow } = require('electron');
const isDev = require('electron-is-dev');
function createWindow() {
// Create the browser window.
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
},
});
// and load the index.html of the app.
// win.loadFile("index.html");
win.loadURL(
isDev
? 'http://localhost:3000'
: `file://${path.join(__dirname, "./index.html")}`
);
// Open the DevTools.
if (isDev) {
win.webContents.openDevTools({ mode: 'detach' });
}
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(createWindow);
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
When running npm start first, then the exe renders react page inside window.
I need some configuration probably but i could not found it yet.
Since you said it works when you start your server first, I assume you're using the localhost URL both in dev and in prod. When your app is packaged, you should load the file in your window and not the local URL:
const { app } = require("electron");
const windowURL = app.isPackaged
? `file://${path.join(__dirname, "./index.html")}`
: "http://localhost:3000/";
mainWindow.loadURL(windowURL);
The path when your app is packaged might be different depending on your file structure and your build/package configurations. Also, don't forget to add "homepage": "./" on your package.json or you may get a blank page.
I am trying to deploy full stack MERN app from one github repository on render.com. After deploying, my front end and back end work individullay fine but they don't work together. For examle, if I send GET request from Postman to deployed back-end I get data as a response but from front-end static site I don't get any response.
I created Static Site and Web Service connecting a single github repo that contain my front-end and back-end. When deploying back-end console show this error
This is my file structure:
Render Web Service setup:
Name: support-desk-api
Branch: main
Root Directory: e.g. src (Default)
Build Command: yarn (Default)
Start Command: npm run dev
Render Static Site setup:
Name: support-desk
Branch: main
Root Directory: e.g. src (Default)
Build Command: npm run render-postbuild
Publish directory: ./client/build
package.json of root
{
"name": "support-desk",
"version": "1.0.0",
"description": "support ticket app",
"main": "server.js",
"scripts": {
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"clientinstall": "npm install --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"render-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"author": "Arifur Rahaman",
"license": "MIT",
"dependencies": {
"bcryptjs": "^2.4.3",
"colors": "^1.4.0",
"concurrently": "^7.5.0",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"express-async-handler": "^1.2.0",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.3.4"
},
"devDependencies": {
"nodemon": "^2.0.16"
}
}
package.json of client
{
"name": "frontend",
"version": "0.1.0",
"proxy": "http://localhost:5000",
"private": true,
"dependencies": {
"#emotion/react": "^11.9.0",
"#emotion/styled": "^11.8.1",
"#mui/icons-material": "^5.8.4",
"#mui/material": "^5.8.2",
"#reduxjs/toolkit": "^1.8.2",
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.3.0",
"#testing-library/user-event": "^14.2.0",
"axios": "^0.27.2",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-icons": "^4.4.0",
"react-modal": "^3.15.1",
"react-redux": "^8.0.2",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1",
"react-toastify": "^9.0.3",
"toastify": "^2.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
server.js
const express = require('express')
const dotenv = require('dotenv').config()
const { errorHandler } = require('./middleware/errorMiddleware')
const connectDB = require('./config/db')
const PORT = process.env.PORT || 5000;
connectDB()
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use('/api/users', require('./routes/userRoutes'))
app.use('/api/tickets', require('./routes/ticketRoutes'))
//* Serve static assets in production, must be at this location of this file
if (process.env.NODE_ENV === 'production') {
//*Set static folder
app.use(express.static('client/build'));
app.get('*', (req,res) => res.sendFile(path.resolve(__dirname, 'client', 'build','index.html')));
}
app.use(errorHandler)
app.listen(PORT, () => { console.log(`Server is running at ${PORT}`) })
Any help would be appreciated
I am working on a social interface project with MERN Stack technology on windows 10. I am running my frontend on port 3000 and my backend on port 5000 of my localhost. When I perform an operation that requires my frontend to be connected to my backend for example the account creation operation, after submitting the account creation form and clicking on the sign up button, nothing happens and when I 'inspect my react web page at the frontend, I see the following error: Failed to load resource: the server responded with a status of 404 (Not Found). After doing research on the Internet, I understood that this was due to the fact that I passed a bad url to my frontend. However, I don't understand why I'm getting this error.
The contents of my backend .env file:
PORT=5000
MONGO_URI="mongodb://localhost:27017/server"
JWT_SECRET = "12/03/2020"
JWT_EXP = '10h'
ADMIN_EMAIL = ""
ADMIN_PASSWORD = ""
I do not put the other values for security reasons. The contents of my config.js file at the backend:
module.exports = {
PORT: process.env.PORT || 4000,
MONGODB_URI: process.env.MONGODB_URI || "mongodb://localhost:27017/server",
JWT_SECRET: process.env.JWT_SECRET || "itssecret",
JWT_EXP: process.env.JWT_EXPIRE || '10h',
ADMIN_EMAIL: process.env.ADMIN_EMAIL || "admin#gmail.com",
ADMIN_PASSWORD: process.env.ADMIN_PASSWORD || "admin#123",
}
the one from my index.js file at the backend:
const express = require('express')
const cors = require('cors')
const mongoose = require('mongoose')
require("dotenv").config()
const app = express()
const http = require('http')
const socket = require("socket.io");
const server = http.createServer(app)
//The modifications are here
const io = socket(server, {
cors: {
origin: "http://localhost:3000",
credentials: true,
},
});
const UserRoutes = require('./routes/User')
const AuthRoutes = require('./routes/Auth')
const PostRoutes = require('./routes/Post')
const PORT = process.env.PORT || 5000
const {MONGODB_URI} = require("./config")
app.use(cors())
app.use(express.json())
app.use((req, res, next) => {
io.req = req
req.io = io
next()
})
app.use('/api/auth', AuthRoutes)
app.use('/api/user', UserRoutes)
app.use('/api/post', PostRoutes)
require('./socket')(io)
mongoose
.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => {
console.log('database connected')
server.listen(PORT, () => console.log(`server started on port ${PORT}`))
})
.catch((err) => console.log(err))
here is the change i made to the index.js file to fix the problem, but nothing; I change the declaration line of my constante io:
const io = require('socket.io')(server)
the definition of the routes at the backend:
router.post('/signup', SignupUser)
router.post('/login', LoginUser)
router.get("/logout",authRequired,Logout)
router.put("/update_password",authRequired,ChangePassword)
module.exports = router
here is my frontend package.json file:
{
"name": "firebase",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.9.0",
"#emotion/styled": "^11.8.1",
"#fortawesome/fontawesome-svg-core": "^6.1.1",
"#fortawesome/free-brands-svg-icons": "^6.1.1",
"#fortawesome/free-regular-svg-icons": "^6.1.1",
"#fortawesome/free-solid-svg-icons": "^6.1.1",
"#fortawesome/react-fontawesome": "^0.1.18",
"#material-ui/core": "^4.12.4",
"#material-ui/icons": "^4.11.3",
"#material-ui/lab": "^4.0.0-alpha.61",
"#mui/material": "^5.8.1",
"#react-google-maps/api": "^2.11.8",
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.2.0",
"#testing-library/user-event": "^13.5.0",
"axios": "0.27.2",
"classnames": "2.2.6",
"dotenv": "8.2.0",
"emoji-picker-react": "^3.5.1",
"firebase": "^9.8.4",
"install": "^0.13.0",
"jwt-decode": "3.1.2",
"moment": "^2.29.3",
"node-fetch": "^3.2.4",
"npm": "^8.11.0",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-eva-icons": "0.0.8",
"react-hook-google-maps": "^0.0.3",
"react-moment": "^1.1.2",
"react-router-dom": "5.3.3",
"react-scripts": "5.0.1",
"socket.io-client": "4.5.1",
"words-to-numbers": "1.5.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"web-vitals": "^2.1.4"
}
}
Here is my backend socket.js file:
const User = require('./models/User')
const jwt = require('jsonwebtoken')
module.exports = (io) => {
io.on('connection', (socket) => {
if (io.req) {
socket.broadcast.emit('friend-login-status', { user_id: io.req.userId })
addSocketIdInDB(socket.id, io.req.userId)
socket.on('disconnect', () => {
socket.broadcast.emit('friend-logout-status', {
user_id: io.req.userId,
})
io.req.userId = null
})
}
})
}
async function addSocketIdInDB(socket_id, user_id) {
const user = await User.findById(user_id)
if (socket_id) {
user.socketId = socket_id
}
await user.save()
}
Here is the content of my frontend .env file:
REACT_APP_ENDPOINT = "http://localhost:5000"
Here is the content of my useSignupUser.js file where the error was thrown:
const url = process.env.REACT_APP_ENDPOINT
...
...
const { data } = await axios.post(`${url}/api/auth/signup`, initialState)
localStorage.setItem('token', JSON.stringify(data.data.token))
const me = await fetchCurrentUser()
setLoading(false)
To solve this error, I modified the data constant declaration line as well, but without success:
const { data } = await axios.post(`http://localhost:5000/api/auth/signup`, initialState)
I obtain this error to the following url:
http://localhost:3000/%22http://localhost:5000%22/api/auth/signup
I looked on this stackoverflow question but nothing. So I hope to rely on the community. Thanks.
I found the solutions to my problem.
Solution 1 :
In the frontend .env file, write without quotes:
REACT_APP_ENDPOINT = http://localhost:5000
instead of:
REACT_APP_ENDPOINT = "http://localhost:5000"
Solution 2 (only in developer mode) :
For this, I edited my package.json file of the backend:
{
"name": "backend",
"version": "1.0.0",
"license": "MIT",
"main": "index.js",
"type": "commonjs",
"scripts": {
"dev": "concurrently \"npm start\" \"npm run client\"",
"start": "node index.js",
"server": "nodemon index.js",
"client": "npm start --prefix frontend"
},
"dependencies": {
"bcrypt": "^5.0.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "4.17.1",
"jsonwebtoken": "^8.5.1",
"mongodb": "^3.7.3",
"mongoose": "^5.10.7",
"multer": "^1.4.2",
"socket.io": "^4.4.1"
},
"devDependencies": {
"concurrently": "^7.2.2",
"nodemon": "^2.0.4"
}
}
For those who don't know, I advise you to use concurrently , it allows you to run two commands at the same time from one; here i am using it to start my backend and frontend server from npm run dev command. This is very practical when working in MERN Stack.
I added this line on my frontend package.json file:
"proxy": "http://127.0.0.1:5000",
this solves the cors error which prevents a domain in my case localhost:3000 from communicating with another for example localhost:5000. This error is due to a restriction used to reduce the risk of site hacking via other.
And I modified the files of the frontend where the API was called in this way:
const { data } = await axios.post(`/api/auth/signup`, initialState)
instead of
const { data } = await axios.post(`{$url}/api/auth/signup`, initialState)
The reason is that since I added a proxy to my package.json file, I no longer need to specify my server's port number in my frontend files because the connection is automatic.
I'm currently trying to set up Jest in my React project. I have created a simple snapshot test for App.js. I heard that you cannot run Jest without Babel so I used npm i babel-jest to install them both at the same time. I feel like I have done everything the normal tutorials have asked me to do. However, when I run `npm run test' I get the following error message:
PS C:\XXXXXXXXXXX\git\react-project\client> npm run test
> react-project#0.1.0 test C:\XXXXXXXXXXXX\git\react-project\client
> jest
FAIL src/App.test.js
● Test suite failed to run
SyntaxError: C:\XXXXXXXXXX\git\react-project\client\src\App.test.js: Support for the experimental syntax 'jsx' isn't currently enabled (6:32):
4 |
5 | it ('renders correctly', () => {
> 6 | const tree = renderer.create(<App />).toJSON();
| ^
7 | expect(tree).toMatchSnapshot();
8 | });
Add #babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
at Parser._raise (node_modules/#babel/parser/src/parser/error.js:60:45)
at Parser.raiseWithData (node_modules/#babel/parser/src/parser/error.js:55:17)
at Parser.expectOnePlugin (node_modules/#babel/parser/src/parser/util.js:157:18)
at Parser.parseExprAtom (node_modules/#babel/parser/src/parser/expression.js:1180:18)
at Parser.parseExprSubscripts (node_modules/#babel/parser/src/parser/expression.js:563:23)
at Parser.parseUpdate (node_modules/#babel/parser/src/parser/expression.js:543:21)
at Parser.parseMaybeUnary (node_modules/#babel/parser/src/parser/expression.js:527:17)
at Parser.parseExprOps (node_modules/#babel/parser/src/parser/expression.js:343:23)
at Parser.parseMaybeConditional (node_modules/#babel/parser/src/parser/expression.js:308:23)
at Parser.parseMaybeAssign (node_modules/#babel/parser/src/parser/expression.js:263:21)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 4.303 s
Ran all test suites.
(node:15304) ExperimentalWarning: The fs.promises API is experimental
I feel like the solution is in this error message but I can really understand what they are asking me to do here. Any help would be great! Let me know if you need any more information!
react-project\package.json
{
"name": "react-project",
"version": "1.0.0",
"scripts": {
"client": "cd client && yarn start",
"server": "nodemon server.js"
},
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.4"
},
"devDependencies": {
"concurrently": "^4.0.1",
"nodemon": "^2.0.4"
}
}
react-project\server\server.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/api/hello', (req, res) => {
res.send({ express: 'Helo From Express' });
});
app.post('/api/world', (req, res) => {
console.log(req.body);
res.send(
`I received your POST request. This is what you sent me: ${req.body.post}`,
);
});
app.listen(port, () => console.log(`Listening on port ${port}`));
react-project\client\App.js
import React from 'react';
import './App.css';
function App() {
return (
<div className="App">
Hello
</div>
);
}
export default App;
react-project\client\App.test.js
import React from 'react';
import { renderer } from "#testing-library/react";
import App from './App';
it ('renders correctly', () => {
const tree = renderer.create(<App />).toJSON();
expect(tree).toMatchSnapshot();
});
react-project\client\package.json
{
"name": "react-project",
"version": "0.1.0",
"private": true,
"dependencies": {
"babel-jest": "^26.3.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/core": "^7.11.6",
"#babel/node": "^7.10.5",
"#babel/plugin-transform-react-jsx": "^7.10.4",
"#babel/preset-env": "^7.11.5",
"jest": "^26.4.2",
"nodemon": "^2.0.4"
}
}
"proxy": "http://localhost:3001" in my package.json
where the express server is running on this port ( 3001 ), but every time I am hitting a request from react it's going on 3000 port on which react app is running
package.json
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"antd": "^3.10.2",
"axios": "^0.18.0",
"dotenv": "^6.1.0",
"http-proxy-middleware": "^0.19.0",
"material-ui": "^0.20.2",
"react": "^16.5.2",
"react-bootstrap": "^0.32.4",
"react-dom": "^16.5.2",
"react-form": "^3.5.6",
"react-redux": "^5.0.4",
"react-router-dom": "^4.3.1",
"react-router-redux": "^5.0.0-alpha.5",
"react-scripts": "2.0.5",
"styled-components": "^4.0.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
setupProxy.js
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/api/*', { target: 'http://localhost:3001' }));
};
"proxy": {
"/services": {
"target": "http://localhost:3001",
"changeOrigin": true,
"pathRewrite": {
"^/services": ""
}
}
}
npm start again
You can define the port in your index.js
const PORT = 3001;
and use
"proxy": { "/*": { "target": "http://localhost:3001" } }
in client package.json
for http-proxy-middleware:
install the package.
create a file called setupProxy.js
and inside it use below pattern
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(proxy('/', { target: 'http://localhost:3001' }));
};
Remember to remove the old proxy scripts code from your client side package.json .
If you are using new version http-proxy-middleware ("1.X.X"), the code could be changed to the following:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use('/console/api', createProxyMiddleware({
target: 'http://localhost:8080/',
changeOrigin: true,
pathRewrite: {'^/console/api' : ''}
}));
};
In other words, proxy should be replaced with createProxyMiddleware