2

Cannot retrieve data form MongoDB Atlas Back-end using mongoose and axios. I have been using React hooks and calling the axios get inside my contextProvider after which I dispatch the data to the reducer. I have tried most of the solutions I could find and none seemed to solve the issue. I have been stumbling from one error to the other without having any clue how to solve it.

here is the most frequent error:

Proxy error: Could not proxy request /api/projects from localhost:3000 to http://localhost:5001.
[1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).

I have read the nodejs documentation and understand the request was refused but it doesn't specify how to solve the problem

I would greatly appreciate any pointers

Here is the request:

const getProjects = async () =>{
        try {
        const res = await axios.get("api/projects");
        dispatch({
            type:GET_PROJECT_ALL,
            payload:res
        });
        }catch(err){
            console.log(err);
        }

    }

response:

GET /api/projects 304 69.326 ms - -

Here is the server set-up:

const dbURI = "mongodb+srv://My_Dev:****@*****.*****.mongodb.net/******?retryWrites=true&w=majority";
mongoose.connect(dbURI,{ useNewUrlParser: true, useUnifiedTopology: true}).then((result)=>{
    console.log("connected to my mongodb")
    app.listen(5001,()=>{console.log("connected on port 5001")});
}).catch((err)=> console.log(err.message));


app.use(express.json({extended:true }));
app.use(morgan('dev'));

// setting up cors

var corsOptions = {
    origin: "http://localhost:5001"
  };

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors(corsOptions));



// defining our routes:

// routes handling projects
app.use('/api/projects', require('./routes/projects'));

this is the handler:

router.get('/',async (req,res) => {
    try{
   const projects = await Project.find({private:false})
   .sort({createdAt:-1})
   .populate({path: 'collaborators',select:"memberName"})
   .populate({path: 'roles',select:"roleName"});
   res.send(projects);
    }
    catch (err){
        console.error(err.message);  
        res.status(500).send('Server error');
    }
})

this is how I access it within the react component :

const projectContext = useContext(ProjectContext);
    const {projects, getProjects } = projectContext;

    
    useEffect(() => {
        getProjects()
        console.log(projects.length);
    });

    if(projects.length  === 0 ){
        return <h3>there is nothign to be found ...</h3>
    }

When starting nodemon and concurrently:

(node:13839) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
[0] connected to my mongodb
[0] connected on port 5001
[1] ℹ 「wds」: Project is running at http://192.168.1.23/ 
ncsex
  • 23
  • 4
  • Are you using some proxy or container on your project ? – Juan Rambal Apr 04 '21 at 00:56
  • I have these 2 in package.json folder "proxy": "http://localhost:5001", "secure":false – ncsex Apr 04 '21 at 00:58
  • And in your server if you use express.json() you dont need to use bodyparser.json() – Juan Rambal Apr 04 '21 at 00:58
  • So no containers ? Try writing 127.0.0.1 instead of localhost and add the protocol something like this : "proxy": "http://127.0.0.1:5001", "secure":false. The address with the http at the beginning – Juan Rambal Apr 04 '21 at 01:02
  • No container that I am aware of.I had already tried your suggestion but no luck unfortunately – ncsex Apr 04 '21 at 01:05
  • Try adding a "/" after the port on the proxy, and check from postman or your browser if the server works well – Juan Rambal Apr 04 '21 at 01:08
  • Searching on other similar questions I found a possible solution using wildcards to specify the sub routes, something like this: "proxy": { "/api/**": { "target": "https://127.0.0.1:5001", "secure": false } }, – Juan Rambal Apr 04 '21 at 01:11
  • Just tried the "/" but not working either. The request on postman are working just fine and they show up in the browser on "http://localhost:5001/" which is confusing – ncsex Apr 04 '21 at 01:13
  • Oh :( Obviously the problem is the react proxy but I dont know what could be, check this similar question to see if there's something helpful https://stackoverflow.com/questions/45367298/could-not-proxy-request-pusher-auth-from-localhost3000-to-http-localhost500 – Juan Rambal Apr 04 '21 at 01:19
  • 1
    Will check it out. Thanks a lot for your help :) – ncsex Apr 04 '21 at 01:23

1 Answers1

0

Tried all possible solution that I could find but there seemed to be an unidentifiable error that persisted where multiple ports kept overriding each other. I finally solved it by using the archaic yet always reliable method of turning the computer off and back on. I know it's not the technical answer some might have expected but I hope it will help people consider this option sooner rather than later in the process of resolving a similar issue.

ncsex
  • 23
  • 4