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.