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
}
})
Related
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
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?
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"
}
}
I am trying to upload my app to Heroku which has frontEnd and sending mail backend both are working in my local machine. Please help anyone to solve my issue that will be of great help because this is my first and practice project to be live.
The structures and error are mentions below:
Heroku error
heroku logs --tail
client package.json
{
"name": "hephy-web",
"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.19.2",
"bootstrap": "^4.4.1",
"react": "^16.13.1",
"react-bootstrap": "^1.0.0",
"react-dom": "^16.13.1",
"react-router-dom": "^5.1.2",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"heroku-postbuild": "cd client && npm install && npm run build",
"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"
]
}
}
server package.json
{
"name": "hephy-back-end",
"version": "1.0.0",
"description": "Hephy BackEnd",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Uchom",
"license": "ISC",
"dependencies": {
"#sendgrid/mail": "^7.0.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-handlebars": "^4.0.3",
"nodemailer": "^6.4.6"
}
}
server app.js
require('dotenv').config()
const path = require('path')
var express = require('express');
var router = express.Router();
var nodemailer = require('nodemailer');
var cors = require('cors');
require('dotenv').config()
var transport = {
service: 'gmail',
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS
}
}
var transporter = nodemailer.createTransport(transport)
transporter.verify((error, success) => {
if (error) {
console.log(error);
} else {
console.log('Server is ready to take messages');
}
});
router.post('/send', (req, res, next) => {
var name = req.body.name
var email = req.body.email
var message = req.body.message
var content = `Name: ${name} \n \nE-mail: ${email} \n \nMessage: ${message} `
var mail = {
from: name,
to: 'xxxxxxxxxxx', // Change to email address that you want to receive messages on
subject: 'Hephy Inquiry Contact',
text: content
}
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
status: 'fail'
})
} else {
res.json({
status: 'success'
})
}
})
})
const app = express()
app.use(cors())
app.use(express.json())
app.use('/', router)
app.listen(3005)
// Serve static files from the React frontend app
app.use(express.static(path.join(__dirname, 'client/build')))
it looks like you app listens to port 3005, this wont work on Heroku where you need to bind to the port provided
const PORT = process.env.PORT || 3005;
I built an app using React and Node Js and now I want to deploy it over Firebase. I am new to these frameworks and just couldn't figure out what went wrong.
While running the server locally everything works fine but when I run 'firebase serve' I get a response that says "You need to enable JavaScript to run this app".
The app is deployed here -> Expense Tracker
You can see the XHR request, transactions, in dev tools.
Thanks in advance.
client/package.json:
{
"name": "expense-tracker",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.4.1",
"#testing-library/user-event": "^7.2.1",
"axios": "^0.19.2",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-scripts": "3.4.0"
},
"scripts": {
"start": "react-scripts start",
"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"
]
},
"proxy": "http://localhost:5000"
}
server.js:
const path = require('path');
const express = require('express');
const dotenv = require('dotenv');
const colors = require('colors');
const morgan = require('morgan');
const transactions = require('./routes/transactions');
const connectDB = require('./config/db');
dotenv.config({ path: './config/config.env' });
const app = express();
app.use(express.json());
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
app.use('/api/v1/transactions', transactions);
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'));
});
}
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));
firebase.json:
{
"hosting": {
"public": "client/build",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
},
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
}
}
package.json:
{
"name": "expense-tracker",
"version": "1.0.0",
"description": "Backend for Expense Tracker",
"main": "server.js",
"scripts": {
"start": "node server",
"server": "nodemon server",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
"author": "Keshavram Kuduwa",
"license": "MIT",
"dependencies": {
"colors": "^1.4.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"firebase-admin": "^8.10.0",
"mongoose": "^5.9.4",
"morgan": "^1.9.1"
},
"devDependencies": {
"concurrently": "^5.1.0",
"nodemon": "^2.0.2"
},
"homepage": "."
}
I think you are trying to run this express-node instance as a firebase function
try doing
exports.app = functions.https.onRequest(app);
at the end of your server.js file
OR
create firebase hosting and a firebase function
run your website in firebase hosting and run your node-express instance as a firebase function