how to deploy app to heroku and proxy API request - reactjs

Can you help me find what's wrong when I try to deploy my fullstack app to heroku.
where can I find the solution to make my http requests work ?
I have tried :
adding a proxy in the package.json
using npm http-proxy-middleware
Nothing seems to work ??
This is my index.js
const express = require("express");
const bodyParser = require("body-parser");
require('dotenv').config();
const app = express();
const { createProxyMiddleware } = require("http-proxy-middleware");
const path = require("path");
const routes = express.Router()
const { getAll, getSingle, postArticle, postComment, postVote } = require("./routes");
const cors = require("cors");
app.use(cors());
app.use('/articles', routes);
routes.use("/", getAll);
routes.use("/:id", getSingle)
routes.use("/:id/upvote", postVote);
routes.use("/insert", postArticle);
// create another collection comment
routes.use("/:id/add-comment", postComment);
//middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Step 1:
app.use(express.static(path.resolve(__dirname, "./build")));
// Step 2:
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, './build/index.html'));
});
app.listen(4000, () => {
console.log(`server running on port 4000`);
});
and, package.json
{
"name": "app",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.1.1",
"#testing-library/user-event": "^13.5.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-scripts": "5.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"
]
}
}
404 - NotFound

To make it simple, each request is basically followed by url/route/end-point
https://deploy-mern-2084.herokuapp.com/articles/somthing_else
"something_else" should be replaced with one of your endpoint from your nodejs code at your route file
Please, make sure that your node js is not running at the same url with you react js code

Related

fetch response returns undefined after deploying it to Netlify

I am trying to deploy a MERN stack app using Heroku for the backend, and Netlify for the frontend. After successfully building and deploying the site using Netlify, I encountered the error below when I tried to execute my Login fuction. I have been looking for solutions to similar problems and trying them out but to no avail.
error encountered
I included some files that might be relevant to the issue below.
package.json
{
"proxy": "https://netninja-workouts-app.herokuapp.com",
"name": "frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"date-fns": "^2.29.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.3",
"react-scripts": "5.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"
]
}
}
fetch function from frontend:
const response = await fetch('/api/user/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email, password })
}).then(r => console.log(r))
backend entry file:
// imports
const express = require('express'); // express
require('dotenv').config(); // fetch env variables
const mongoose = require('mongoose'); // mongodb
const workoutRoutes = require('./routes/workouts')
const userRoutes = require('./routes/user')
// start up express app
const app = express()
// middleware - fires for every requests that comes in
app.use(express.json()) // looks for body in the data and attaches it to the request object to allow access to the request handlers
app.use((req, res, next) => {
console.log(req.path, req.method) // logs the request path and method
next() // moves on to the next middleware
})
// reacting to requests - route handlers
app.use('/api/workouts', workoutRoutes)
app.use('/api/user', userRoutes)
// DB Connection - ASYNC in nature (returns a PROMISE)
mongoose.connect(process.env.MONGO_URI)
.then(() => {
// only starts listening when database is connected
app.listen(process.env.PORT, () => {
console.log('Connected to DB and Listening on port', process.env.PORT);
});
})
.catch((error) => {
console.log(error);
})
backend routing:
// imports
const express = require('express')
const { loginUser, signupUser, getUserInfo } = require('../controllers/userController')
// express router object
const router = express.Router()
// route handlers
// get request (req, res) : request object has information about the request AND response object sends data back to the browser/client
// login route - POST
router.post('/login', loginUser)
// signup route - POST
router.post('/signup', signupUser)
// profile route - GET
router.get('/profile', getUserInfo)
// export router
module.exports = router
I greatly appreciate and welcome suggestions and help.

Why proxy did not work in React when I try to post data to Laravel backend API?

1.Now i'm building a React-Laravel app. React.js is frontend and Laravel is backend. React is running on port http://localhost:3000 and Laravel is running on port http://127.0.0.1:8000. I set up proxy on package.json file to be http://127.0.0.1:8000. Here is the code for package.json file.
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.2",
"#testing-library/react": "^12.1.3",
"#testing-library/user-event": "^13.5.0",
"axios": "^0.26.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^6.2.2",
"react-scripts": "^5.0.0",
"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"
]
},
"proxy": "http://localhost:8000"
}
2.Then I tried to do some very simple tests, send data to Laravel back end (\signin route).Here are the code for frontend and backend
export default function Login(){
function handleSubmit (event) {
event.preventDefault();
fetch("/signin", {
method:"POST",
cache: "no-cache",
headers:{
"content_type":"application/json",
},
body:JSON.stringify({username: 'example' })
}
).then(response => {
return response.json()
})
// .catch((error) => console.log(error.message));
};
return (
<div>
<NavBar />
<PageHeading headingName={"Playground Manager Login"} />
<form className="form-signin" onSubmit={handleSubmit}>
<br/><br></br>
<EmailInputText />
<PasswordInputText />
<ForgotPasswordLabel/>
<SignupButton />
</form>
<Footer />
</div>
)
}
Laravel :
Route::post('/signin', function(Response $response) {
return $response;
});
Then I got the error below. The remote request url is http://localhost:3000/signin. I think this one should be http://localhost:8000/signin since I set up the proxy in the package.json file. Can someone tell me why the proxy did not work properly?

React Express Built app not working in production mode

I have a Create React App working well in development mode both with
yarn start
and
yarn build > serve -s build
But when I upload my build folder to my distant server (on Planet Hoster), I get the following errors :
GEThttps://www.mysite.fr/static/js/main.f79317f8.js
[HTTP/2 404 Not Found 273ms]
GEThttps://www.mysite.fr/static/css/main.43a07738.css
[HTTP/2 404 Not Found 272ms]
What's happening here ? I've been working days and days on it and I still can't find something... Any help will be greatful !
My code to launch my express server :
const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname, "build")));
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "build", "index.html"));
});
[EDIT] - Here is my package.json file if it can helps :
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.1",
"#testing-library/react": "^12.1.2",
"#testing-library/user-event": "^13.5.0",
"axios": "^0.25.0",
"cors": "^2.8.5",
"express": "^4.17.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router": "^6.2.1",
"react-router-dom": "^6.2.1",
"react-router-hash-link": "^2.4.3",
"react-scripts": "5.0.0",
"web-vitals": "^2.1.4",
"webpack": "^5.67.0"
},
"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"
]
}
}
I am coming back to it lately but I finally found the solution.
To achieve it, I ran locally node app.js wich is the file that launch my frontend service. I then found in my logs that my script was trying to "modify the headers of my site after they were sent". I fix it and now it works.
My code was probably not that clean.
Still, thank you for your help !

WebSocket error when React app is deployed

I receive this error:
webpackHotDevClient.js:60 WebSocket connection to 'wss://{url}/sockjs-node' failed: ./node_modules/react-dev-utils/webpackHotDevClient.js
{"name": "packspace",
"version": "0.1.0",
"private": true,
"dependencies": {
"#loadable/component": "^5.14.1",
"#material-ui/core": "^4.11.4",
"#material-ui/icons": "^4.11.2",
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"web-vitals": "^1.0.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"
]
}
}
// Connect to WebpackDevServer via a socket.
var connection = new WebSocket(
url.format({
protocol: window.location.protocol === 'https:' ? 'wss' : 'ws',
hostname: process.env.WDS_SOCKET_HOST || window.location.hostname,
port: process.env.WDS_SOCKET_PORT || window.location.port,
// Hardcoded in WebpackDevServer
pathname: process.env.WDS_SOCKET_PATH || '/sockjs-node',
slashes: true,
})
);
// Unlike WebpackDevServer client, we won't try to reconnect
// to avoid spamming the console. Disconnect usually happens
// when developer stops the server.
connection.onclose = function () {
if (typeof console !== 'undefined' && typeof console.info === 'function') {
console.info(
'The development server has disconnected.\nRefresh the page if necessary.'
);
}
};
Working in React app and the app is deployed to server. It is working normally on localhost but I am getting the error that above at the title when I enter the deployed URL with https or http. I checked the answer in React app error: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS but my file is already like that.
How can I fix that error?

Seeing a blank page on deploying create-react-app application to heroku

No webpack config since I have not ejected. I'm seeing an empty root div.
This is my package.json
{
"name": "ttt",
"version": "0.1.0",
"homepage": "https://tictactoezz.herokuapp.com/",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"express": "^4.17.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.2"
},
"scripts": {
"start": "node server/server.js",
"build": "react-scripts build",
"test": "react-scripts test",
"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"
]
}
}
This is my server/server.js
const path = require('path');
const express = require('express');
const app = express();
const publicPath = path.join(__dirname, '../public');
const port = process.env.PORT || 3000;
app.use('/static', express.static(publicPath));
app.get('*', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
app.listen(port, () => {
console.log('Server is up!');
});
Please help! Unlike other questions posted here, I do not see any errors in the console.. just a blank screen. It works on localhost:3000
You don't need to have server.js for heroku deployment if you use create-react-app. In case you insist to have server.js, it should point build folder, not public folder. You need to run npm run build first and then server.js should server contents on build folder. You can add a new script for heroku-post-build.
...
"heroku-postbuild": "npm run build"
...
It doesn't look like your start script includes building the react app. Can you try this?
"scripts": {
"prestart": "npm run build",
"start": "node server/server.js",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
I have struggled with the same problem for two days. Express&React.js app was working fine on localhost but not on heroku. I added this to server.js and problem solved.
app.use(express.static(path.join(__dirname, './frontend/build')));
My react.js folder had the name "frontend" and it was at the same level with my server.js file. And don't remove build name and dont change it to any other name. build is a default folder for your react app to launch.

Resources