1

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.

gks
  • 191
  • 1
  • 4
  • 18
  • Does this help? [404 Not Found when trying to install ESLint 8.4.4 with create-react-app](https://stackoverflow.com/q/72821442/1839439) – Dharman Jun 30 '22 at 22:22
  • It doesn't help me because this problem I get when I run my react app in my browser console not when I install a package or create a new project and I'm using `npm 8.11.0` . Thanks for the help anyway. Have a nice evening. – gks Jun 30 '22 at 22:40
  • are you sure that you are writing correctly the url? – Angel Hdz Jun 30 '22 at 22:57
  • Yes, I wrote the url correctly according to me and as I said everything runs on the localhost, `localhost:5000`. is the server execution address of my backend. – gks Jun 30 '22 at 23:36
  • Can you show the code of the API you are hitting on the backend and `package.json` of the frontend? – Daniyal Malik Jul 02 '22 at 05:58
  • I edited my question. I don't really know what you call api file, I guess you mean my `socket.js` file. I'm new to `MERN` and I'm not very familiar with some technical terms and for that I'm sorry. Maybe you can clarify things for me if that's not what you call api file. For my part, I added my `package.json` file from the frontend and `socket.js` from the backend. Thanks – gks Jul 02 '22 at 08:36
  • I am unable to find the solution to your problem. The only way left is to run your application and debug it on my system. Kindly upload your whole MERN code to a Github repo and provide the link here. – Daniyal Malik Jul 03 '22 at 11:49
  • I edited my question and added my git links – gks Jul 03 '22 at 21:14
  • 1
    You don't put quotes into `.env` files. They adhere to the INI file format. Eg `REACT_APP_ENDPOINT=http://localhost:5000` – Phil Jul 07 '22 at 06:13

1 Answers1

1

I found the solutions to my problem.

Solution 1 :

In the frontend .env file, write without quotes:

REACT_APP_ENDPOINT = http://localhost:5000

instead of:

REACT_APP_ENDPOINT = "http://localhost:5000"

Solution 2 (only in developer mode) :

For this, I edited my package.json file of the backend:

    {
  "name": "backend",
  "version": "1.0.0",
  "license": "MIT",
  "main": "index.js",
  "type": "commonjs",
  "scripts": {
    "dev": "concurrently \"npm start\" \"npm run client\"",
    "start": "node index.js",
    "server": "nodemon index.js",
    "client": "npm start --prefix frontend"
  },
  "dependencies": {
    "bcrypt": "^5.0.0",
    
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongodb": "^3.7.3",
    "mongoose": "^5.10.7",
    "multer": "^1.4.2",
    "socket.io": "^4.4.1"
  },
  "devDependencies": {
    "concurrently": "^7.2.2",
    "nodemon": "^2.0.4"
  }
}

For those who don't know, I advise you to use concurrently , it allows you to run two commands at the same time from one; here i am using it to start my backend and frontend server from npm run dev command. This is very practical when working in MERN Stack. I added this line on my frontend package.json file:

"proxy": "http://127.0.0.1:5000",

this solves the cors error which prevents a domain in my case localhost:3000 from communicating with another for example localhost:5000. This error is due to a restriction used to reduce the risk of site hacking via other. And I modified the files of the frontend where the API was called in this way:

const { data } = await axios.post(`/api/auth/signup`, initialState)

instead of

const { data } = await axios.post(`{$url}/api/auth/signup`, initialState)

The reason is that since I added a proxy to my package.json file, I no longer need to specify my server's port number in my frontend files because the connection is automatic.

gks
  • 191
  • 1
  • 4
  • 18