React app not hitting url described in proxy ( package.json file ) - reactjs

"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

Related

Can't deploy full stack MERN project on render

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

Deploying React, Express project to Heroku

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"
]
}
}

React JS API calls to http://localhost:8000/index.php using axios not working after npm run build

After performing npm run build on my app, I am not able to make requests to my PHP backend at port 8000. It works when I am running it via npm start, but it suddenly does not work when I serve the build folder using serve -s build.
I have confirmed that my backend server is working.
Here is my package.json file:
{
"name": "name",
"version": "0.1.0",
"proxy": "http://localhost:8000/index.php",
"homepage": ".",
"dependencies": {
"#material-ui/core": "^4.12.4",
"#material-ui/icons": "^4.11.3",
"#material-ui/lab": "^4.0.0-alpha.61",
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.2.0",
"#testing-library/user-event": "^13.5.0",
"axios": "^0.27.2",
"bootstrap": "^5.1.3",
"http-proxy-middleware": "^2.0.6",
"jquery": "^3.6.0",
"material-ui-icons": "^1.0.0-beta.36",
"qs": "^6.10.3",
"react": "^18.1.0",
"react-bootstrap": "^2.3.1",
"react-dom": "^18.1.0",
"react-hooks-global-state": "^1.0.2",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1",
"react-select": "^3.2.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"
]
}
}
Reverse proxy
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = (app) => {
app.use(
createProxyMiddleware("/test", {
target: "http://localhost:8000/index.php",
changeOrigin: true,
})
);
app.use(
createProxyMiddleware("/login", {
target: "http://localhost:8000/index.php",
changeOrigin: true,
})
);
app.use(
createProxyMiddleware("/getAllRooms", {
target: "http://localhost:8000/index.php",
changeOrigin: true,
})
);
app.use(
createProxyMiddleware("/updateRoom", {
target: "http://localhost:8000/index.php",
changeOrigin: true,
})
);
app.use(
createProxyMiddleware("/AddNewRoom", {
target: "http://localhost:8000/index.php",
changeOrigin: true,
})
);
app.use(
createProxyMiddleware("/logout", {
target: "http://localhost:8000/index.php",
changeOrigin: true,
})
);
app.use(
createProxyMiddleware("/register", {
target: "http://localhost:8000/index.php",
changeOrigin: true,
})
);
};
Again it works on npm start, but not on npm run build.

Cypress returns "browserslist" error in Create React App?

I've got a very simple Create React App that I am trying to implement Cypress with. I initially had a different but related error that I was able to overcome. I'm not entirely sure why I would be given this type of error considering I do have the default "browserslist" key in my package.json file.
package.json
{
"name": "cypress_test",
"version": "0.1.0",
"private": true,
"engines": {
"node": "16.13.1",
"npm": "8.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"cypress": "cypress open",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"dependencies": {
"#cypress/react": "^5.12.4",
"#cypress/webpack-dev-server": "^1.8.4",
"#emotion/react": "^11.9.0",
"#emotion/styled": "^11.8.1",
"#fontsource/roboto": "^4.5.5",
"#mui/icons-material": "^5.6.2",
"#mui/material": "^5.6.3",
"#mui/styled-engine-sc": "^5.6.1",
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^12.1.5",
"#testing-library/user-event": "^13.5.0",
"browserslist": "^4.6.3",
"cypress": "^9.6.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.1",
"sass": "^1.51.0",
"styled-components": "^5.3.5",
"web-vitals": "^2.1.4"
},
"devDependencies": {
"#babel/core": "^7.17.9",
"#babel/preset-env": "^7.16.11",
"#cypress/webpack-preprocessor": "^5.11.1",
"babel-loader": "^8.2.5",
"eslint-plugin-cypress": "^2.12.1",
"html-webpack-plugin": "^4.5.2",
"webpack": "^5.72.0"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"overrides": [
{
"extends": [
"plugin:cypress/recommended"
],
"files": [
"cypress/**/*.js"
]
}
],
"resolutions": {
"#mui/styled-engine": "npm:#mui/styled-engine-sc#latest"
},
"jest": {
"coveragePathIgnorePatterns": [
"<rootDir>/cypress/"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
When I initially installed CRA, it used the latest version of React 18, but apparently Cypress doesn't have support for 18 yet so I downgraded React to 17. I'm wondering if there are some sort of package mismatches that I'm unaware of and aren't receiving specific errors for. As a note though, the app runs fine in the browser. Here are the other related files:
/cypress/plugins/index.js:
const findWebpack = require('find-webpack')
const webpackPreprocessor = require('#cypress/webpack-preprocessor');
const injectDevServer = require('#cypress/react/plugins/react-scripts');
module.exports = (on, config) => {
const webpackOptions = findWebpack.getWebpackOptions();
if (!webpackOptions) {
throw new Error('Could not find Webpack in this project');
}
const cleanOptions = { reactScripts: true };
findWebpack.cleanForCypress(cleanOptions, webpackOptions);
const options = {
webpackOptions,
watchOptions: {},
};
on('file:preprocessor', webpackPreprocessor(options));
injectDevServer(on, config);
return config;
};
App.spec.js:
import React from 'react';
import data from '../fixtures/data.json';
import App from '../../src/App.jsx';
describe('Test search functionality', () => {
beforeEach(() => {
cy.mount(<App />);
});
it('renders new fact when search is performed', () => {
cy.visit('http://localhost:3001')
// Type in search input
cy.get('input').type('Test');
// Click on search button
cy.get('.submit-btn').click();
// Intercept the request and return the mock data
cy
.intercept({
method: 'GET',
url: `${process.env.REACT_APP_API_ENDPOINT}/jokes/search?query=Test`
}, {
fixture: data.result[1]
})
.as('fetchFact');
// cy.wait(['#fetchFact']);
cy.get('p.copy').should('contain', data.result[1].value);
})
});
cypress.json:
{
"baseUrl": "http://localhost:3001",
"videos": false,
"component": {
"testFiles": "**/*.cy.{js,ts,jsx,tsx}",
"componentFolder": "src"
}
}
Cypress error:
Error: No browserslist config found to handle the 'browserslist' target.
See https://github.com/browserslist/browserslist#queries for possible ways to provide a config.
The recommended way is to add a 'browserslist' key to your package.json and list supported browsers (resp. node.js versions).
You can also more options via the 'target' option: 'browserslist' / 'browserslist:env' / 'browserslist:query' / 'browserslist:path-to-config' / 'browserslist:path-to-config:env'
at TARGETS.web (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/config/target.js:93:11)
at getTargetProperties (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/config/target.js:296:19)
at /Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/config/target.js:342:20
at Array.map (<anonymous>)
at getTargetsProperties (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/config/target.js:342:11)
at applyWebpackOptionsDefaults (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/config/defaults.js:142:6)
at createCompiler (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/webpack.js:77:2)
at create (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/webpack.js:134:16)
at webpack (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/webpack.js:158:32)
at f (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/index.js:63:16)
at Object.handler (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/#cypress/webpack-preprocessor/dist/index.js:148:24)
at invoke (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_plugins.js:22:16)
at /Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/util.js:45:14
at tryCatcher (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/node_modules/bluebird/js/release/util.js:16:23)
at Function.Promise.attempt.Promise.try (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/node_modules/bluebird/js/release/method.js:39:29)
at Object.wrapChildPromise (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/util.js:44:23)
at Object.wrap (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/preprocessor.js:28:8)
at execute (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_plugins.js:123:27)
at EventEmitter.<anonymous> (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_plugins.js:213:5)
at EventEmitter.emit (node:events:390:28)
at process.<anonymous> (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/util.js:19:22)
at process.emit (node:events:390:28)

http-proxy-middleware not working on Heroku

I made a front end SPA with create-react-app. I implemented http-proxy-middleware to solve CORS issues with api calls to https://api.deezer.com. The proxy works flawlessly locally, but it fails to add the headers after deploying to Heroku and the res.data from the api calls is undefined in the console.
Here is my setupProxy.js in my /src folder.
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
proxy("/chart", {
target: "https://api.deezer.com",
changeOrigin: true
})
)
app.use(
proxy("/artist", {
target: "https://api.deezer.com",
changeOrigin: true
})
)
app.use(
proxy("/search", {
target: "https://api.deezer.com",
changeOrigin: true
})
)
app.use(
proxy("/album", {
target: "https://api.deezer.com",
changeOrigin: true
})
)
}
And my api calls look like this (one example):
getTopHits() {
return(
axios.get('/chart')
)
}
And here is my package.json:
{
"homepage": "https://secret-hamlet-05097.herokuapp.com/",
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"axios": "^0.21.1",
"fetch-jsonp": "^1.1.3",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.3"
},
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
"dev": "react-scripts start",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"heroku-postbuild": "npm run build"
},
"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": {
"gh-pages": "^3.1.0",
"http-proxy-middleware": "^0.19.1"
}
}
What could be wrong?

Resources