Okay so guys, I created a small note taking web-app on MERN stack. The front-end is running at localhost:3000, and the backend is running at localhost:5000, I am getting all the requests and response from the backend using axios. In the backend I’m using app.use(cors()) to avoid any connection issues.
So the issue is, It works perfectly on the pc I’m hosting it on, but when I try to access it from my another device (which is connected to the same wifi as my pc) my putting :3000 in the address bar, it shows the frontend, but when I try to save notes or get them, it doesn’t work. But when I visit :8000/get, I can see my all notes saved there.
So the final issue is, it’s working perfectly on the hosted device, but another device (connected to the same wifi) the front-end and back-end isn’t working together, however they are accessible when separately visiting their respective ports.
For ease, I’ll attach my main react component file, and server.js file
Create.jsx (Main react component)
"use client"
import React, { useState, useEffect } from 'react'
import axios from "axios";
function Create(){
useEffect(()=>{
axios.get("http://localhost:5000/get")
.then(result => setnotes(result.data))
.catch(err => console.log(err))
}, [])
const [notes, setnotes]= useState([]);
const [note, setnote]=useState();
const addNote=()=>{
axios.post("http://localhost:5000/add", {note: note})
.then(result => console.log(result))
.catch(err => console.log(err));
document.getElementById("input").value=""
}
const removeNote=(id)=>{
axios.delete("http://localhost:5000/delete/"+id)
.catch(err => console.log(err))
}
return(
<div>
<textarea className='form' placeholder='Enter note' onChange={(e)=>setnote(e.target.value)} name="" id="input" cols="30" rows="10"></textarea>
<br />
<button onClick={addNote} className="button" type="button">Create</button>
{
notes.length===0
?
<div><h2>No notes at the moment</h2></div>
:
notes.map(note => (
<>
<div className='result'>
{note.note}
</div>
<button onClick={()=> removeNote(note._id)} className='delete'>Delete</button>
</>
))
}
</div>
)
}
export default Create
server.js (server entry point)
const express=require('express');
const mongoose=require("mongoose");
const cors=require("cors");
const collection=require("./models/note.js");
mongoose.connect("mongodb+srv://<username>:<password>@cluster0.fetyubc.mongodb.net/")
const app=express();
app.use(cors());
app.use(express.json());
app.get("/get", (req, res)=>{
collection.find()
.then(result => res.json(result))
.catch(err => console.log(err));
})
app.post("/add", (req, res)=>{
const note=req.body.note;
collection.create({
note: note
}).then(result => res.json(result))
.catch(err => console.log(err))
})
app.delete("/delete/:id", (req, res)=>{
const {id}=req.params;
collection.findByIdAndDelete({_id: id})
.then(result => res.json(result))
.catch(err => console.log(err));
})
app.listen(5000, ()=>{
console.log("server is running")
})