PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label mern. Show all posts
Showing posts with label mern. Show all posts

Thursday, October 13, 2022

[FIXED] How do I display specific entries in mongoDB to react front end with axios

 October 13, 2022     axios, mern, mongodb, reactjs     No comments   

Issue

//brief context of application

In my application a user can customise a microreactor (type of object that has many attributes) and then save it which gets saved to mongoDB. The application runs on the MERN stack. After the user creates it, they can view it on a different page.

//the problem

When the user views the microreactors that have been created, ALL microreactors are being shown, microreactors that have been created by other users. I only want microreactors that have been created by the active user to be shown to them.

//how I'm trying to solve it

Here is the schema:

const mongoose = require("mongoose");

const MicroreactorSchema = new mongoose.Schema({

    user: {
        type: String
    },

    name: {
        type: Number 
    },

    electrodeOne: {
        type: String
    },

    electrodeTwo: {
        type: String
    },

    temperature: {
        type: String
    },
    
    pressure: {
        type: String
    },

    flowRate: {
        type: String
    },

    reagentOne: {
        type: String
    },

    reagentTwo: {
        type: String

    },

    electrodeArea: {
        type: String
    },

    electrodeDistance: {
        type: String
    },

    vcTemp: [
        String,
    ],
    
    vcTempTime: [
        String
    ],

    vcPressure: [
        String,
    ],

    vcPressureTime: [
        String,
    ],

    vcFlowRate: [
        String,
    ],

    vcFlowRateTime: [
        String
    ],

    tubing: [{
        length: String,
        diameter: String,
        loops: String,
        material: String}]

});

const MicroreactorsModel = mongoose.model("microreactors", MicroreactorSchema);

module.exports = MicroreactorsModel;


As you can see the microreactor has the attribute user, this user correlates to the specific user who created the microreactor at the time of creating/saving it.

This is the code that fetches the microreactors and displays it to the user (in the react front end)

useEffect(() => {
        Axios.get("http://localhost:3001/getMicroreactors").then((response) => {
            setMrViewList(response.data);
            
            
            
        });

        
        
    }, []);

This code fetches all microreactors. I want the one that match to the active user. This is the code (below) I tried. I don't think it's possible this way. Any suggestions would be greatly appreciated


 useEffect(() => {
        Axios.get("http://localhost:3001/getMicroreactors").then((response) => {
            
          
           

                for(let i=0; i<response.data.length; i++) {
   
                    response.data[i].map((mr) => {
                        if(mr.user == localStorage.getItem("userUsername")) {
                            setMrViewList(...mrViewList, response.data[i])

                        }

                    }
                )}
            
            
        });

in response to a question results.data is an object type and is shown as this enter image description here

As requested the whole code:

import React from 'react';
import { useState, useEffect, useRef} from 'react';
import Axios from 'axios';
import { AccordionSummary } from '@material-ui/core';
import { LocalConvenienceStoreOutlined, RepeatOneSharp, SettingsBackupRestoreOutlined } from '@material-ui/icons';


const View = () => {
    //how parse works
    let w = '["wow", "wowww"]';
    const a = JSON.parse(w);
    // list of micro reactors already created shown in the first row that correlate to session 
    const [mrViewList, setMrViewList] = useState([]);

    // list of all microreactors regardless of username
    const [mrViewListSelected, setMrViewListSelected] = useState([]);

    //state showing time shown in the bottom middle column
    //seconds
    const [timers, setTimers] = useState(0);
    //tens of seconds
    const [timerst, setTimerst] = useState(0);
    //mins
    const [timerm, setTimerm] = useState(0);
    //tens of minutes
    const [timermt, setTimermt] = useState(0);
    //hours
    const [timerh, setTimerh] = useState(0);
    //tens of hours
    const [timerht, setTimerht] = useState(0);
    //turns the timer on and off

    const [timerToggle, setTimerToggle] = useState(false);

    //switches run button to stop upon pressing

    const [buttonStateRun, setButtonStateRun] = useState(true);
    const [buttonStateStop, setButtonStateStop] = useState(false);

    //state that will hide/show the run/stop buttons upon clicking

    const [showStop, setShowStop] = useState(false);

    //state that will show the selected microreactors variable conditions that have been qued
    const [col3vc, setCol3vc] = useState("");

    //states will update the variable conditions qued when a mircroreactor is clicked on

    const [col2Temp, setCol2Temp] = useState("");
    const [col2TempTime, setCol2TempTime] = useState("");
    const [col2Pressure, setCol2Pressure] = useState("");
    const [col2PressureTime, setCol2PressureTime] = useState("");
    const [col2FlowRate, setCol2FlowRate] = useState("");
    const [col2FlowRateTime, setCol2FlowRateTime] = useState("");

    //states will update the variable conditions that have been executed in col 1

    const [col1Temp, setCol1Temp] = useState("");
    const [col1TempTime, setCol1TempTime] = useState("");
    const [col1Pressure, setCol1Pressure] = useState("");
    const [col1PressureTime, setCol1PressureTime] = useState("");
    const [col1FlowRate, setCol1FlowRate] = useState("");
    const [col1FlowRateTime, setCol1FlowRateTime] = useState("");

    //states that will show the times set in h:m:s format
    const [timeT, setTimeT] = useState([]);
    const [timeP, setTimeP] = useState([]);
    const [timeF, setTimeF] = useState([]);

    const [dbTimer, setDbTimer] = useState();
    let dbTimerCounter = 1;

    //state that shows what button has been clicked
    const [microReactorClicked, setMicroReactorClicked] = useState(false);

    //error which will render if run has been clicked without microreactor clicked
    const [microReactorClickedError, setMicroReactorClickedError] = useState();

    const [runButtonClicked, setRunButtonClicked] = useState(false);

    const [runButtonClickedError, setRunButtonClickedError] = useState("");
    

    




    let secs = 0;
    let secsTens = 0;
    let mins = 0;
    let minsTens = 0;
    let hours = 0;
    let hoursTens = 0;

    //instantly increments as set interval will delay by 1s on the first iteration
    const instantIncrements = () => {
        secs ++;
    }

    let tempArray = [];

    const timerid = useRef(0);
    // timer that starts when the run button is clicked
    const startTimer = () => {

        if (microReactorClicked) {
            //sorting out states of what was clicked and not to avoid repeats etc
            setRunButtonClicked(true);
            setMicroReactorClickedError("");
            setDbTimer(0);

            setButtonStateRun(false);
            setButtonStateStop(true);
            //avoids a double delay on first iteration
            instantIncrements();

            tempArray = col2Temp.split(" ");

            timerid.current = setInterval(() => {
                
                if (secs === 10) {
                    secs = 0;
                    //fixes a delay on first increment of secsTens
                    if (secsTens === 0) {
                        setTimerst(1);
                        secsTens = 1;
                    // increments minute by 1 once 60 seconds reached
                    } else if (secsTens === 6) {
                        //fixes a delay on the first incremenet of minute
                        if (mins === 0) {
                            setTimerm(1);
                            mins = 1;
                        //increments tens of minutes after 10 minutes reached
                        } else if (mins === 10) {
                            //fixes a delay in the first increment of minuteTens
                            if (minsTens === 0) {
                                setTimermt(1);
                                minsTens = 1;
                            //increments hour by one once 60 minutes reached
                            } else if (minsTens === 6) {
                                minsTens = 0;
                                setTimermt(0);
                                //fixes delay on first hour
                                if (hours === 0) {
                                    setTimerh(1);
                                    hours = 1;
                                } else if (hours === 10) {
                                    hours = 0;
                                    setTimerh(0);
                                    //fixes delay on first hourTens
                                    if(hoursTens === 0) {
                                        setTimerht(1);
                                        hoursTens = 1;
                                        
                                    }
                                    setTimerht(hoursTens ++);
                                }
                                setTimerh(hours ++);
                            } 
    
                            setTimermt(minsTens ++);
                            
                            mins = 0
    
                            
                        }
                        
                        secsTens = 0;
                        setTimerm(mins ++);
                    }
                    setTimerst(secsTens ++);
                }
                setTimers(secs ++);

                // this part of the counter will listen into the counter wait until the queued conditions time match the timer and will then move them into the executed conditions column
                /*let temporaryCol2Temp = "";

                for (let i=0; i < runTempTime.length; i++) {
                    
                    console.log("iteration " + i + "and value of col2Temp is " + temporaryCol2Temp);
                    if(dbTimerCounter == runTempTime[i]) {        
                        //if col2 has comma find the index of comma
                        console.log("iteration found time to do something");
                        
                        if (col2Temp.includes(',')) {
                            temporaryCol2Temp = col2Temp;                         
                            let indexPoint = temporaryCol2Temp.indexOf(',') + 1;
                            temporaryCol2Temp = temporaryCol2Temp.slice(indexPoint);
                            setCol2Temp(temporaryCol2Temp);
                        } else {
                            setCol1Temp(col2Temp);
                            setCol1TempTime(col2TempTime);
                            setCol2Temp("");
                            setCol2TempTime("");
                        }
                    } else {
                        //console.log(dbTimerCounter + "i is" + i + "runtemp is" + runTemp[i] );
                    }
                }
                */
                
                dbTimerCounter ++;
            }, 1000);

        } else {
            setMicroReactorClickedError("please select a microreactor");
        }
        /* 
        pseudo;
            if microreactor selected run
            else generate error
            check if it has been clicked first
        */
    }

    const startTimerTwo = () => {
        
    }

    const stopTimer = () => {
        setRunButtonClicked(false);
        clearInterval(timerid.current);
        timerid.current = 0;
        setButtonStateRun(true);
        setButtonStateStop(false);
        secs = 0;
        secsTens = 0;
        mins = 0;
        minsTens = 0;
        hours = 0;
        hoursTens = 0;
        setTimers(0);
        setTimerst(0);
        setTimerm(0);
        setTimermt(0);
        setTimerh(0);
        setTimerht(0);
        setCol1Temp("");
        setCol1TempTime("");
        setCol1Pressure("");
        setCol1PressureTime("");
        setCol1FlowRate("");
        setCol1FlowRateTime("");
    }

    
    //states that will be used when the run button is clicked to check if time condition has been satisfied to then move from col3 to col1 
    const [runTemp, setRunTemp] = useState([]);
    const [runTempTime, setRunTempTime] = useState([]);
    const [runPressure, setRunPressure] = useState([]);
    const [runPressureTime, setRunPressureTime] = useState([]);
    const [runFlowRate, setRunFlowRate] = useState([]);
    const [runFlowRateTime, setRunFlowRateTime] = useState([]);

    useEffect(() => {
        Axios.get("http://localhost:3001/getMicroreactors").then((response) => {
            
            setMrViewList(response.data);
        });
    }, []);

    /*
    useEffect(() => {
        Axios.get("http://localhost:3001/getMicroreactors").then((response) => {
        const { data } = response;
        const microreactors = data.find((mr) => mr?.user === localStorage.getItem("userUsername"));
        setMrViewList(microreactors);
        });
    }, []);
    */

    //this state will be responsible for showing the user only microreactors they have created
    //the state is set to an axios get request of the microreactor user attribute

    const deleteMicroreactor = (id) => {
        Axios.delete(`http://localhost:3001/delete/${id}`);
        setMrViewList(mrViewList.filter((val) => {
            return val.id != id;
        }))
    }
    
    const [test1, setTest1] = useState("00:33:22s");
    const[test2, setTest2] = useState("");
    
    return (
        <div>
            <div className='viewContainer'>
                <div className='viewCol1'>
                    <div>Saved Microreactors:</div>
                    {/* 
                    
                    dsfjsdfs
                    sdsd
                    fsd
                    fsdfds
                    fsdfsd
                    fsdf
                    setDetailsFsd
                    fs
                    detailsFsdf
                    sdf
                    sd
                    fs
                    df
                    sdfsdf
                    sd
                    fs
                    df
                    sd
                    fsdfsdfds
                    f
                    sdfsd
                    fsd
                    fs
                    df
                    sd
                    fsdf
                    sdffs
                    df
                    sd
                    fs
                    df
                    sdfs
                    dfsdf
                    sd
                    fs
                    fs
                    */}
                    
                    <button onClick={() => {console.log(tempArray)} }>Check data</button>
                    <div className='view3Buttons'>
                        {mrViewList.map((mr) => {
                            return (
                                <div key={mr.name} onClick={() => {
                                    if (runButtonClicked === false) {
                                        setMicroReactorClicked(true);
                                        setMicroReactorClickedError("");
                                        
                                        //converting string into list
                                        let listVcTemp = JSON.parse(mr.vcTemp);
                                        let listVcTempTime = JSON.parse(mr.vcTempTime);
                                        let listVcPressure = JSON.parse(mr.vcPressure);
                                        let listVcPressureTime = JSON.parse(mr.vcPressureTime);
                                        let listVcFlowRate = JSON.parse(mr.vcFlowRate);
                                        let listVcFlowRateTime = JSON.parse(mr.vcFlowRateTime);

                                        setRunTemp(listVcTemp);
                                        setRunTempTime(listVcTempTime);
                                        setRunPressure(listVcPressure);
                                        setRunPressureTime(listVcPressureTime);
                                        setRunFlowRate(listVcFlowRate);
                                        setRunFlowRateTime(listVcFlowRateTime);
                                        
                                        //e.g col2TempString is a string that will have all the list elements inserted into it from vcTemp in the database to be displayed in col2
                                        let col2TempString = "";
                                        let col2TempTimeString = "";
                                        let col2PressureString = "";
                                        let col2PressureTimeString = "";
                                        let col2FlowRateString = "";
                                        let col2FlowRateTimeString = "";
                                        //e.g concats the data together from the vcTemp
                                        for(let i=0; i<listVcTemp.length; i++) {
                                            col2TempString = col2TempString.concat(listVcTemp[i] + ", ");
                                        }
                                        //gets rid of the final ", " in the string and then sets the state to the string
                                        col2TempString = col2TempString.slice(0, -2);
                                        setCol2Temp(col2TempString);
    
                                        let finalListT = [];
                                        //same but for temp time
                                        for(let i=0; i<listVcTempTime.length; i++) {
                                            //converting to int
                                            let temporaryIterationT = parseInt(listVcTempTime[i]);
                                            //finding a floored values to get number of hours
                                            let hoursT = Math.floor(temporaryIterationT / 3600);
                                            //same for mins and seconds respectively
                                            let minsT = Math.floor((temporaryIterationT - (hoursT * 3600))/60);
                                            let secsT = Math.floor(temporaryIterationT - (hoursT * 3600) - (minsT * 60));
                                            //setting states to update the new time format as a formatted string
                                            let finalString = `${hoursT}h:${minsT}m:${secsT}s`;
                                                finalListT.push(finalString)
    
                                            col2TempTimeString = col2TempTimeString.concat(finalListT[i] + ", ");
                                        }
                           
                                        col2TempTimeString = col2TempTimeString.slice(0, -2);
                                        setCol2TempTime(col2TempTimeString);
    
                                        //same but for pressure
                                        for(let i=0; i<listVcPressure.length; i++) {
                                            col2PressureString = col2PressureString.concat(listVcPressure[i] + ", ");
                                        }
                                     
                                        col2PressureString = col2PressureString.slice(0, -2);
                                        setCol2Pressure(col2PressureString);
                                        
                                        let finalListP = [];
                                        //same but for pressure time
                                        for(let i=0; i<listVcPressureTime.length; i++) {
                                            //converting to int
                                            let temporaryIterationP = parseInt(listVcPressureTime[i]);
                                            //finding a floored values to get number of hours
                                            let hoursP = Math.floor(temporaryIterationP / 3600);
                                            //same for mins and seconds respectively
                                            let minsP = Math.floor((temporaryIterationP - (hoursP * 3600))/60);
                                            let secsP = Math.floor(temporaryIterationP - (hoursP * 3600) - (minsP * 60));
                                            //setting states to update the new time format as a formatted string
                                            let finalString = `${hoursP}h:${minsP}m:${secsP}s`;
                                                finalListP.push(finalString)
                                            col2PressureTimeString = col2PressureTimeString.concat(finalListP[i] + ", ");
                                        }
                
                                        col2PressureTimeString = col2PressureTimeString.slice(0, -2);
                                        setCol2PressureTime(col2PressureTimeString);
    
                                        //same but for flowRate
                                        for(let i=0; i<listVcFlowRate.length; i++) {
                                            col2FlowRateString = col2FlowRateString.concat(listVcFlowRate[i] + ", ");
                                        }
                                        col2FlowRateString = col2FlowRateString.slice(0, -2);
                                        setCol2FlowRate(col2FlowRateString);
    
                                        let finalListF =[];
                                        //same but for flowRate Time
                                        for(let i=0; i<listVcFlowRateTime.length; i++) {
                                            //converting to int
                                            let temporaryIterationF = parseInt(listVcFlowRateTime[i]);
                                            //finding a floored values to get number of hours
                                            let hoursF = Math.floor(temporaryIterationF / 3600);
                                            //same for mins and seconds respectively
                                            let minsF = Math.floor((temporaryIterationF - (hoursF * 3600))/60);
                                            let secsF = Math.floor(temporaryIterationF - (hoursF * 3600) - (minsF * 60));
                                            //setting states to update the new time format as a formatted string
                                            let finalString = `${hoursF}h:${minsF}m:${secsF}s`;
                                                finalListF.push(finalString)
                                            col2FlowRateTimeString = col2FlowRateTimeString.concat(finalListF[i] + ", ");
                                        }
    
                                        col2FlowRateTimeString = col2FlowRateTimeString.slice(0, -2);
                                        setCol2FlowRateTime(col2FlowRateTimeString);
                                    }

                                    }
                                    
                                }>
                                    <div>Microreactor number: {mr.name}</div>
                                    <button>View</button>
                                    <button>Delete</button>
                                </div>
                            )
                        })}
                        
                    </div>
                </div>
                <div className='viewCol2'>
                    <div className="viewContainer2">
                        <div className='view2Col1'>
                            <div>
                                Variable condition changes executed:
                            </div>
                            <div>
                                Temperature: {col1Temp}
                            </div>
                            <div>
                                Time: {col1TempTime}
                            </div>
                            <div>
                                Pressure: {col1Pressure}
                            </div>
                            <div>
                                Time: {col1PressureTime}
                            </div>
                            <div>
                                FlowRate: {col1FlowRate}
                            </div>
                            <div>
                                Time: {col1FlowRateTime}
                            </div>

                        </div>
                        <div className='view2Col2'>
                            Time elapsed: {timerht}{timerh}h:{timermt}{timerm}m:{timerst}{timers}s
                            {buttonStateRun && <button onClick={startTimer}>Run</button>}
                                    {buttonStateStop && <button onClick={stopTimer}>Stop</button>}
                            
                            {microReactorClickedError}
                            {runButtonClickedError}

                        </div>
                        <div className='view2Col3'>
                            <div>
                                Variable Conditions qued:
                            </div>
                            <div>
                                Temperature: {col2Temp}
                            </div>
                            <div>
                                Time: {col2TempTime}
                            </div>
                            <div>
                                Pressure: {col2Pressure}
                            </div>
                            <div>
                                Time: {col2PressureTime}
                            </div>
                            <div>
                                FlowRate: {col2FlowRate}
                            </div>
                            <div>
                                Time: {col2FlowRateTime}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default View

Response to question: first data type map doesn't work, second data type of object map works

enter image description here


Solution

Instead of a for-loop, what about .filter():

useEffect(() => {
    Axios.get("http://localhost:3001/getMicroreactors").then((response) => {
    const { data } = response;
    const microreactors = data.filter((mr) => mr?.user === localStorage.getItem("userUsername"));
    setMrViewList(microreactors);
    });
};


Answered By - C. Helling
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, August 5, 2022

[FIXED] How to store socket on localStorage/use socket on different components on vanilla ReactJS for use in different components socket.io?

 August 05, 2022     javascript, mern, reactjs, socket.io, sockets     No comments   

Issue

I want to store the socket so I can use it in different components. When I first set the socket on socket.io after login, I set the socket as a state under "socket" state and then store it on localStorage.

useEffect(() => {
        if(!socket) {
            setSocket(io(backendLink));
        };
    }, []) 

useEffect(() => {
        socket?.emit("newUser", localStorage.getItem('authToken'));
        localStorage.setItem('socket', JSON.stringify(socket));
    }, [socket])

Then in different components, where I did not initially set the socket. I use logic like this:

useEffect(() => {
        if(!socket) socket = localStorage.getItem('socket');
        socket.emit(...)
}, [userID])

Above, if the socket passed as props that was stored in state is null, i restore the socket from localStorage and use it to emit. However, I get Uncaught TypeError: Converting circular structure to JSON.

From what I understood, this is because I used JSON.stringify on something that cannot be converted and stored on localStorage this way i.e socket. I want to use vanilla reactjs to use the socket across as different files from the file i used setSocket(io(backendLink)). How to use socket.io across different components with vanilla reactJS(no context, completely vanilla)?


Solution

You should not stringify such objects, if you want to reference it across your application, you need to just to place it inside a React context after you saved it in the state. That way you can access it wherever you want across your application. There are other options too, but that's the safer one.



Answered By - Cesare Polonara
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to resolve: Failed to load resource: the server responded with a status of 404 (Not Found) in Reactjs

 August 05, 2022     axios, mern, reactjs, socket.io     No comments   

Issue

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.


Solution

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.



Answered By - gks
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, August 1, 2022

[FIXED] How do I set my VPS Webmin/Virtualmin server to show data from MongoDB in the hosted website?

 August 01, 2022     mern, mongodb, virtualmin, vps, webmin     No comments   

Issue

This is my first question I hope I do it right. So :

I developed a MERN website, on which I have perfect connection with a MongoDB db as well as an Amazon S3 one.

I am currently trying to host it on a Hostinger VPS with Virtualmin and Webmin. The data is in thanks to FTP working, so the website design shows but the mongoDB data is missing.

So far :

  • DNS set properly,
  • SSH all good,
  • mongo shell installed inside of server through the console, I can see my db and the data
  • new user created successfully with mongo method db.createUser(), attached to my db

So my question is : what are the following steps to make the way to data, through the server, to the website ?

I'm new to this and I've searched for several days now everywhere without any success, and the hosting support is lost on the matter...

Thanks!


Solution

In case it helps anyone I did succeed in setting up the server, it's quite a bit of work. Here's my config :

  • I set Nginx to listen to the https requests from the front and send them to the back. The config file is called "default", in the folder sites-available, and has the following content :
server {
  listen  80;
  listen 443 ssl;

  root /the/frontend/root/folder;
  server_name _;
  
  ssl on;
  ssl_certificate /the/ssl/.crt/file;
  ssl_certificate_key /the/ssl/.key/file;

  # react app & front-end files
  location / {
    try_files $uri /index.html;
  }

  # node api reverse proxy
  location /api/ {
    proxy_pass http://localhost:portlistenedbybackend/api/;
  }
}
  • The React frontend comes with a .env file that is integrated in the build. In it I set the url to where the frontend sends requests (these are then caught by Nginx). Be careful to set this url to the domain of your website when deploying, so in my case : https://example.com/api

  • The production process manager pm2 is useful to keep alive the backend at all times so I installed it and used it for the Node backend. The command to add the backend main server file (in my case server.js) to pm2 from the console : sudo pm2 start your/serverfile/address

  • Here's a couple of links that proved very useful to understand how to configure the server :

    • Applicable to Amazon server but a lot applicable here too : https://jasonwatmore.com/post/2019/11/18/react-nodejs-on-aws-how-to-deploy-a-mern-stack-app-to-amazon-ec2

    • A guide to log journal in console for debugging : https://www.thegeekdiary.com/beginners-guide-to-journalctl-how-to-use-journalctl-to-view-and-manipulate-systemd-logs/

    • For setting up Webmin server : https://www.serverpronto.com/kb/cpage.php?id=Webmin

At first I discarded Webmin and Virtualmin since all I could find (from support included) was tutorials to setup the server via console. So bits by bits I set it up. Then, finally, I got from the support a tuto to setup the server from Webmin. But to this day I can't say wether that made a difference in the structure. But at least it's clean.

  • Last but not least, a couple of console commands I found very useful :

systemctl status theserviceyouwanttosee

systemctl start theserviceyouwanttostart

systemctl stop theserviceyouwanttostop

systemctl restart theserviceyouwanttorestart

Examples of services : nginx, mongod...

Test if Nginx is setup properly : sudo nginx -t

reload nginx config file after any modification : sudo nginx -s reload

See the last errors logged by nginx : sudo tail -f /var/log/nginx/error.log

Save current pm2 settings : pm2 save

Backend execution logs : sudo pm2 logs

Identify the processes still running with mongo (useful if mongod won't restart properly) : pgrep mongo

Kill the mongo process to be able to start fresh : kill <process>

Show all services used by server : sudo systemctl

See all processes in execution and stats of the CPU amongst other things : top

I'm still new to all of this despite my couple of weeks on the subject so this description is most probably improvable. don't hesitate to suggest any improvement, mistake, or ask questions, I'll do my best to answer them.

Cheers!



Answered By - ebrun
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I deploy a MERN stack application to cpanel on a VPS server

 August 01, 2022     cpanel, deployment, hosting, mern, vps     No comments   

Issue

Please anybody with the experience of deploying a MERN stack APP to cpanel on a VPS server? Kindly share! Thanks!!


Solution

You can upload an app to cpanel, that is developed using node,express and react (and in this case, you must ensure first that the cpanel supports nodejs apps, not all of them do so). But, mongoDB simply is not supported by CPanel. You can upload MERN stack app, but, the db won't be connected.

  1. Once you have the cpanel access, create a folder to the directory, upload your project (make sure you take the integrated approach to deploy your mern app).
  2. Go to the UI, create an app and address the folder to the app. Start the app. And your website is ready to use.


Answered By - Tina
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, July 13, 2022

[FIXED] How should and can deploy my mern application

 July 13, 2022     mern, mongodb, node.js, reactjs, web-deployment     No comments   

Issue

Before provide my problem , i'd like to let you know that i am new to developpind web applications and deploy only a couple of projects on Netlify .Besides English is not my native for sure.As for the subject , i developped a mern application which inspired mostly shamahoque projects from github .Our folders tree are the same exactly and i use mongo atlas. I cannot deploy it to Netlify because ive got template.js for MUI server-side rendering on main folder , instead of index.html.When i was searching for this topic , i encountered solutions with docker and nginx but i got barely knowledge about them and not know any roadmap to learn them without youtube tutorials.For conclusion , I really need your help deploying this app on shared hosts like hostinger or at least heroku or netlify. I'd be so grateful for your help.


Solution

Do following:-

  1. Seprate the frontend and backend code into two separate github repositories.
  2. Deploy the Frontend to Netlify/heroku/vercel.
  3. Deploy the backend to Heroku(only heroku support servers)
  4. You can set any environment variable using Environment variables in Netlify and config vars in Heroku.


Answered By - Puneet56
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to connect and deploy React app with Node js backend?

 July 13, 2022     mern, node.js, reactjs, web-deployment     No comments   

Issue

I have completed my first project in MERN stack but now I am struggling to deploy it on hiroku. Till now I was running both react and node code on different ports.

This are the files

enter image description here

client folder is frontend(React). App.js in Node is

const express = require("express");
const app = express();

const userRouter = require("./routes/userRoutes");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const compression = require("compression");

app.use(cors());

app.use(cookieParser());

app.use(express.urlencoded({ extended: true, limit: "10kb" }));
app.use(compression());

app.use("/api/v1/users", userRouter);
module.exports = app;

App.js in React is

import React from "react";
import "./App.css";
import Home from "./mainPages/home";
import Register from "./components/authentication/register";

import { Route, Switch } from "react-router-dom";

function App() {
  return (
    <div className="app">
      
      <Switch>
        <Route
          exact
          path="/"
          component={() => (<Home/>)} />
        <Route
          exact
          path="/register"
          component={() => (<Register/>)} />
        
      </Switch>
    </div>
  );
}

export default App;

Registeration data from client side is send like this

axios({ method: "POST", url: "http://localhost:3000/api/v1/user/register", data: data, headers: header });

How to connect client and server to deploy on hiroku?


Solution

It is ideal to keep client folder outside server folder.

Step 1: Build your React App and take out the contents in the output folder (dist folder)

Step 2: Deploy your front end in any static hosting services eg(AWS S3 or in any hosting providers)

Step 3: Deploy your back end API in Heroku or any node hosting provider

Step 4: Update the AJAX end points in front end.

Step 5: Thoroughly test and release



Answered By - Arun
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing