My react frontend not establishing connection with my node backend - node.js

I am trying to get my react frontend to establish connection with my node backend. The node backend works when I am using PostMan. I have gone through most of the options suggested on this plateform but none is helping.
This is the Fetch request in react
import axios from 'axios'
// Sending Request to register User
let URL = "/user/"
const register = async (userData) => {
let response = await axios.post(URL + 'register', userData)
if (response.data) {
localStorage.setItem('user', JSON.stringify(response.data))
}
return register.data
}
This is my package.json file for the react:
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"options": {
"allowedHosts": [
"localhost",
".localhost"
],
"proxy":"http://localhost:8000"
},
"dependencies": {
"#reduxjs/toolkit": "^1.8.6",
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^14.4.3",
"axios": "^1.1.2",
"bootstrap": "^5.2.2",
"react": "^18.2.0",
"react-bootstrap": "^2.5.0",
"react-dom": "^18.2.0",
"react-icons": "^4.4.0",
"react-redux": "^8.0.4",
"react-router-dom": "^6.4.2",
"react-scripts": "5.0.1",
"react-toastify": "^9.0.8",
"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"
]
}
}
This is my Node index.js file to handle the post request
require('dotenv').config()
const express = require('express')
const bodyParser = require('body-parser')
const { connectToDb } = require('./database/db');
const cors = require('cors')
const port = process.env.PORT || 5000
connectToDb();
const app = express()
app.use(express.json())
app.use(bodyParser.urlencoded({extended:true}))
app.use(cors())
app.use('/user', require('./routes/userRoutes'))
app.listen(port, () => {
console.log(`Server is running on ${port}`)
})
What should am I not doing right?

Related

Why i'm not able to GET while deploying in heroku? but locally it can postable

I'm new for mern development and my app was not able to fetch post while deployment in heroku.
I have no idea about this.
i was attached procfile web:node app.js also
after that also i'm not able to fetch post
it return 503 error
{
"name": "site",
"version": "1.0.0",
"engines": {
"node": "16.17.0",
"npm": "8.15.0"
},
"description": "site for buying AR and VR product",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"author": "Farooq",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.6",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.7.0",
"pg": "^8.8.0"
},
"devDependencies": {
"nodemon": "^2.0.20"
}
}
my app.js file
const express = require('express');
const dotenv = require('dotenv');
const cookieParser = require('cookie-parser')
const port = process.env.PORT||5000;
const app = express();
const path = require('path')
// const path = require('path')
dotenv.config({path:"./config.env"})
require('./db/conn')
const userSchema = require('./model/userSchema');
app.use(cookieParser())
app.use(express.json())
app.use(require('./routes/auth'))
if(process.env.NODE_ENV === 'production'){
app.use(express.static("client/build"))
app.get("*", (req, res)=>{
res.sendFile(path.resolve(__dirname, 'client', "build", "index.html"))
})
}
app.listen(port, ()=>{
console.log(`site is listening at port ${port}`)
})
client folder package.js
{
"name": "client",
"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",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.2",
"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"
]
},
"devDependencies": {
"autoprefixer": "^10.4.12",
"postcss": "^8.4.18",
"tailwindcss": "^3.1.8"
}
}
I need to fetch the data by post method while deployment

"Cannot GET /" error message in heroku browser page

I get an error where the heroku page in browser just return this error Cannot GET / and when I am console log , it is saying 404 error but i have no idea on the error, already change the HTTPS to HTTP in server index.js .Any there change that I need to make ? Already tried other solution also not working fine it still have an error with the server, how can i fix this. Below i attach server index.js and my package.json.
server index.js
const express = require("express");
const app = express();
const http = require("https");
const { Server } = require("socket.io");
const cors = require("cors");
const server = http.createServer(app);
const user = [];
app.use(cors());
const io = new Server(server, {
cors: {
origin: "http://testing.herokuapp.com/" + (process.env.PORT || 5000),
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
user.push(socket.id);
socket.on("join_room", (data) =>{
socket.join(data);
})
socket.on("send_message", (data) => {
let new_data = {user_id: data.id, msg: data.text};
socket.to(data.room).emit("receive_message", new_data);
})
});
server.listen(process.env.PORT || 5000, () => {
console.log("SERVER OK");
});
package.json
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.2.0",
"#testing-library/user-event": "^13.5.0",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "5.0.1",
"socket.io-client": "^4.5.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"
]
},
"devDependencies": {
"autoprefixer": "^10.4.7",
"postcss": "^8.4.14",
"react-router-dom": "^6.3.0",
"tailwindcss": "^3.0.24"
}
}

Cannot connect server to client in node.js

I'm trying to connect my client to my server using socket.io to connect them. However it doén't seem to work since i don't get the socket.id in my terminal and i get this error Cannot GET / in my localhost. Please help me to fix it. Thank you so much!
client:
App.js:
import "./App.css";
import io from "socket.io-client";
const socket = io.connect("http://localhost:3000");
function App() {
return <div className="App"></div>;
}
export default App;
package.json:
{
"name": "client",
"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",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.0",
"socket.io-client": "^4.4.0",
"web-vitals": "^2.1.2"
},
"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:
index.js:
const express = require("express");
const app = express();
const http = require("http");
const cors = require("cors");
const {
Server
} = require("socket.io");
app.use(cors());
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
console.log(`User connected: ${socket.id}`);
socket.on("disconnect", () => {
console.log("User Disconnected", socket.id);
});
})
server.listen(3000, () => {
console.log("SERVER RUNNING");
});
package.json:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"connect": "^3.7.0",
"cors": "^2.8.5",
"express": "^4.17.2",
"nodemon": "^2.0.15",
"socket.io": "^4.4.0"
}
}
For this example, the working code for the socket.io
let express = require('express');
let app = express();
let server = require('http').createServer(app);
let io = require('socket.io')(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
credentials: true
}
})

I want to deploy my React application on Heroku but I am getting the error cannot get/ after my application is deployed

Picture of my React application with all the files
My src files
I am unable to deploy my application on Heroku.
My package.json for outer (backend) file
{
"name": "teams-clone",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js && cd client && npm start"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"redis": "^3.1.2",
"socket.io": "^4.1.2"
}
}
My server.js file
require("dotenv").config();
const express = require("express");
const http = require("http");
const bodyParser = require("body-parser");
const cors = require("cors");
const port = process.env.PORT;
const app = express();
const server = http.createServer(app);
const Routes = require("./app/routes");
app.use([
cors(),
bodyParser.json(),
bodyParser.urlencoded({ extended: false }),
Routes,
]);
const io = (module.exports.io = require("socket.io")(server, {
cors: {
origin: "*",
},
}));
const socketManager = require("./app/socketManager");
io.on("connection", socketManager);
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
My client package.json file:
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^1.2.35",
"#fortawesome/free-solid-svg-icons": "^5.15.3",
"#fortawesome/react-fontawesome": "^0.1.14",
"#syncfusion/ej2-react-schedule": "^19.1.69",
"#testing-library/jest-dom": "^5.14.0",
"#testing-library/react": "^11.2.7",
"#testing-library/user-event": "^12.8.3",
"axios": "^0.21.1",
"date-fns": "^2.22.1",
"ejs": "^3.1.6",
"express": "^4.17.1",
"moment": "^2.29.1",
"node-sass": "^4.14.1",
"react": "^17.0.2",
"react-calendar": "^3.4.0",
"react-dom": "^17.0.2",
"react-icons": "^4.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"shortid": "^2.2.16",
"simple-peer": "^9.11.0",
"socket.io": "^4.1.2",
"socket.io-client": "^4.1.2",
"web-vitals": "^1.1.2"
},
"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 also have this piece of code for socket connections in my client:
let peer = null;
const socket = io.connect("http://localhost:4000");
const initialState = [];
I have changed it to the heroku link while deploying instead of local host 4000
my apiEndpints BASE_URL now is:
http://localhost:4000
which I changed it to the heroku link while deploying instead of local host 4000
How my application starts is:
first switch on Redis.exe -> node server.js -> cd client -> npm start
I also made a Procfile with=> web: node server.js
What am I doing wrong?

My react node app not reading data from backend after deploying on heroku

I am able to run my project locally without any errors but on heroku it's stuck on initial login/signup page. I assume that's because it's not interacting with the backend and only displaying frontend.
This is what my project structure looks like,
Project Structure
Content of package.json of my root folder which is react frontend
frontend/package.json
{
"name": "cook-it",
"version": "0.1.0",
"private": true,
"dependencies": {
"#apollo/react-hooks": "4.0.0",
"#material-ui/core": "4.11.3",
"#material-ui/lab": "4.0.0-alpha.57",
"#testing-library/jest-dom": "5.11.9",
"#testing-library/react": "11.2.5",
"#testing-library/user-event": "12.8.0",
"add": "2.0.6",
"antd": "4.15.0",
"apollo-cache-inmemory": "1.6.6",
"apollo-client": "2.6.10",
"apollo-link-context": "1.0.20",
"apollo-link-http": "1.5.17",
"firebase": "8.3.1",
"graphql": "15.5.0",
"graphql-tag": "2.11.0",
"jwt-decode": "3.1.2",
"react": "17.0.1",
"react-bootstrap": "1.5.1",
"react-dom": "17.0.1",
"react-router-dom": "5.2.0",
"react-scripts": "4.0.3",
"semantic-ui-css": "2.4.1",
"semantic-ui-react": "2.0.3",
"web-vitals": "1.1.0",
"yarn": "^1.22.10"
},
"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"
]
}
}
frontend/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App';
import 'antd/dist/antd.css';
import { ApolloProvider } from '#apollo/react-hooks';
import ApolloClient from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { AuthProvider } from './context/auth';
import 'semantic-ui-css/semantic.min.css'
const httpLink = createHttpLink({
uri: 'http://localhost:5000/'
});
const authLink = setContext(() => {
const token = localStorage.getItem('jwtToken');
return {
headers: {
Authorization: token ? `Bearer ${token}` : ''
}
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
ReactDOM.render(
<ApolloProvider client={client}>
<AuthProvider>
<App />
</AuthProvider>
</ApolloProvider>,
document.getElementById('root')
);
frontend/backend/package.json
{
"name": "merng",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"serve": "nodemon index",
"start": "node index"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"apollo-server": "^2.24.0",
"bcryptjs": "^2.4.3",
"csvtojson": "^2.0.10",
"graphql": "^14.3.1",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.12.7",
"react-router-dom": "^5.0.1",
"semantic-ui-css": "^2.4.1",
"semantic-ui-react": "^0.87.2"
},
"devDependencies": {
"nodemon": "^1.19.1"
}
}
frontend/backend/index.js
const { ApolloServer } = require('apollo-server');
const mongoose = require('mongoose');
const typeDefs = require('./graphql/typeDefs');
const resolvers = require('./graphql/resolvers');
const { MONGODB } = require('./config.js');
const ports = process.env.PORT || 5000
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => ({ req })
});
mongoose
.connect(MONGODB, { useNewUrlParser: true,useUnifiedTopology: true })
.then(() => {
console.log('MongoDB Connected');
return server.listen({ port: ports });
})
.then((res) => {
console.log(`Server running at ${res.url}`);
});
You deployed your backend to heroku
But did not update backend url in your frontend app
const httpLink = createHttpLink({
uri: 'http://localhost:5000/' // <-- here
});

Resources