skip to Main Content

I have page of notes, and when user click on each note, I make a request to backend (basically a get request that get invoked on onClick event when clicking on the note) to check if that user who made the request is owner of this note or not, however the request is not being processed at all.

I am using Next.ts on frontend:


  const handleOpenDialog = async (note:Note)=>{
        const data = await fetch(`http://127.0.0.1:8000/notes/${note.slug}/`,{credentials:'include'})
        console.log(data)


    }


function mapNotes(){
        return(
        notes.map((note,i)=>{
            return(
            <div onClick={()=>handleOpenDialog(note)} key={note.slug} id={note.slug} className='noteContainer'>
      
                <div className='headerSection'>
                    <div className='likeDiv'>
                        LIKES HERE
                    </div>
                    <div className='copyDiv'>
                        COPY ICON HERE
                    </div>
                </div>
                <div className='upperSection'>
                <div className='noteTitle'>
                    {note.title}
                </div>
            <div className='noteDesc'>
                {note.description.slice(0,10)+'...'}
            
            </div>
            </div>

            <div className='lowerSection'>
                <div className='noteUser'>
                    {note.username}
                </div>
                <div className='noteDate'>
                    {note.date}
                </div>
                <div className='noteSpace'>
                    {note.space}
                </div>
            </div>

            <div className='footerSection'>
                <div className='socialSection'>
                    <div className='facebook'>
                        FB
                    </div>
                    <div className='twitter'>
                        X
                    </div>
                    <div className='reddit'>
                        RDT
                    </div>
                    <div>
                        AM I THE OWNER OF THIS NOTE? {note.isOwner}
                    </div>
                </div>
            </div>

            
        <Dialog  id={note.slug} open={dialogId == note.slug} onClose={()=>setDialogId('')}>

            <div className='closeBtn' >
                    <button onClick={()=>setOpen(false)}>Close</button>

                </div>
                <div className='noteExpand'>
                    <div className='likeSection'>
                        LIKES HERE
                    </div>
                    <div className='titleSection'>

                        <div className='title'>
                            {note.title}
                        </div>

                        {!activateTextEdit?<div className='descSection'>
                        {note.description}</div>: <TextareaAutosize className='desc' name='description' value={desc} onChange={(e)=>handleDescEditChange(e,note)}/>}
                    

                        <div className='space'>
                            {note.space}
                        </div>
                        <div className='user'>
                            {note.username}
                        </div>
                        <div className='date'>
                            {note.date}
                        </div>

                    </div>
                 
                </div>
                <div className='modify'>
                    {note.isOwner?<div>
                        {activateTextEdit?<button className='edit' onClick={()=>setActivateTextEdit(true)}>Edit</button>:<button onClick={(e)=>clickOnEdit(e,note)}  className='editSub'>Submit</button>}
                        <button className='delete'>Delete</button>
                        <div>{error}</div>
                    </div>:null}
                </div>
                </Dialog>

            </div>

            
            
            )
        })

        )
    }

the route in backend (Express):

router.get('/notes/:slug',async (req:Request,res:Response)=>{
    // this route is triggered when client is accessing a specific note dialog
    //the purpose of this route is to check if the user on the other side is the owner of that note.
    console.log('hello')

    const param = req.params.slug
    const user = await pool.query('SELECT user FROM note WHERE slug = $1 ',[param])
    if(req.session!.userId == user.rows[0]){
        res.status(200).json({isOwner:true})
    }
    else{
        res.status(401).json({isOwner:false})
    }
})

regarding logging, I tried logging "hello world" inside handleOpenDialog function before the fetch function and it is being logged, however, it seem that fetch request is not being processed at all, in addition, nothing in the backend is being logged.

EDIT:

Here is my CORS settings in backend:


app.use(cors({
    'origin':['http://localhost:3000','http://127.0.0.1:3000'],
    'credentials':true,
}))

My frontend origin is : 127.0.0.1:3000

My backend origin is : 127.0.0.1:8000

I allowed the frontend origin

I also want to mention that other routes are working normally on both sides, it is just this specific case that is not working for some reason.

Screenshot on what I see on the network tab:

enter image description here

enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    I found a solution, however I have not yet discovered on why this solve it:

    I changed the route request to post instead of get and it worked:

    express:

    
    router.post('/notes/:slug',async (req:Request,res:Response)=>{
        // this route is triggered when client is accessing a specific note dialog
        //the purpose of this route is to check if the user on the other side is the owner of that note.
    
        const param = req.params.slug
        const user = await pool.query('SELECT "user" FROM note WHERE slug = $1 ',[param])
        console.log(user.rows[0])
        console.log(req.session!.userId)
        if(req.session!.userId == user.rows[0].user){
            res.status(200).json({isOwner:true})
        }
        else{
            res.status(401).json({isOwner:false})
        }
    })
    
    

    in frontend (react/next.js):

    
        const handleOpenDialog = async (note:Note)=>{
                 const data = await fetch(`http://127.0.0.1:8000/notes/${note.slug}/`,{method:'POST',credentials:'include'})
                 console.log(data)
        }
    
    

  2. If your frontend (Next.js app) and backend (Express server) are running on different ports, it’s likely a CORS (Cross-Origin Resource Sharing) issue. By default, browsers restrict cross-origin HTTP requests initiated from scripts. Since your frontend is on a different origin than your backend, you need to enable CORS on your backend.

    Make sure the request URL in your fetch call is correct and the backend server is running and accessible at http://127.0.0.1:8000/.

    Your request URL ends with a trailing slash (/notes/${note.slug}/). Ensure your backend handles routes consistently with or without a trailing slash, as some frameworks or configurations might treat these URLs differently.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search