0

im folowing a tutorial on how to build a tinder clone using MERN STACK and it was working well till i wanted to get the user data and pass it to the chat header ChatHeader it gave me an this error in the backend

server running on PORT8000 Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at new NodeError (node:internal/errors:372:5) at ServerResponse.setHeader (node:_http_outgoing:576:11) at ServerResponse.header (C:\Users\zenati\Desktop\react-project\tinder-clone\server\node_modules\express\lib\response.js:794:10)
at ServerResponse.send (C:\Users\zenati\Desktop\react-project\tinder-clone\server\node_modules\express\lib\response.js:174:12)
at C:\Users\zenati\Desktop\react-project\tinder-clone\server\index.js:84:25 { code: 'ERR_HTTP_HEADERS_SENT' }

and the console.log('user',user) was giving me null

index.js (the backend)

const PORT = 8000
const express = require('express')
const { MongoClient } = require('mongodb')
const { v4: uuidv4 } = require('uuid')
const jwt= require('jsonwebtoken')
const cors = require('cors')
const bcrypt= require('bcrypt')
const uri = 'mongodb+srv://admin:Nokia3600@cluster0.agi9w.mongodb.net/Cluster0?retryWrites=true&w=majority'

const app = express()
app.use(cors())
app.use(express.json())

app.get('/', (req, res) => {
    res.json('Hello to my app')
})




app.post('/signup', async (req, res) => {
    const client = new MongoClient(uri)
    const { email, password } = req.body

    const generateUserId = uuidv4()
    const hashedPassword = await bcrypt.hash(password, 10)
    
    
    try {
        await client.connect()
        const database = client.db('tinderdb')
        const users = database.collection('users')
        const exsistingUser = await users.findOne({ email })
        
        if (exsistingUser) {
            return res.status(409).send('user already exists please login')
        }
        const sanitizedEmail = email.toLowerCase()
        
        const data = {
            user_id: generateUserId,
            email: sanitizedEmail,
            hashed_password: hashedPassword
        }
        
        
        const insertedUser = await users.insertOne(data)
        const token = jwt.sign( insertedUser, sanitizedEmail, {
            expiresIn: 60 * 20
        })

        res.status(201).json({ token, userId: generateUserId })


    } catch(err) {
        console.log(err)
    }finally{
        await client.close()
    }
})


app.post ('/login', async (req, res) => { 
    const client = new MongoClient(uri)
    const { email, password}= req.body
    
    try{
        await client.connect()
        const database = client.db('tinderdb')
        const users = database.collection('users')

        const user = await users.findOne({ email })
        const correctPassword = await bcrypt.compare(password , user.hashed_password)

        if (user && correctPassword) {

            const token= jwt.sign(user ,email, {
                expiresIn : 60*24
            })

          res.status(201).json({token , userId: user.user_id})  

        }
        res.status(400).send('Invalide Credentials')

        
    }catch(err){
        console.log(err)
    }finally{
        await client.close()
    }
    
})



app.get('/user', async (req,res) => {
    const client = new MongoClient(uri)
    const userId = req.query.userId


    try{
        await client.connect()
        const database = client.db('tinderdb')
        const users = database.collection('users')
        const query = {user_id:userId}

        console.log('query',query)
        const user = await users.findOne(query)
        res.send(user)

    }finally{
        await client.close()
    }

})






app.get('/users', async (req, res) => {
    const client = new MongoClient(uri)


    try {
        await client.connect()
        const database = client.db('tinderdb')
        const users = database.collection('users')

        const returnedUsers = await users.find().toArray()
        res.send(returnedUsers)

    } finally {
        await client.close()
    }
})

app.put ('/user' , async (req ,res)=> {
    
    const client = new MongoClient(uri)
    const formData = req.body.formData
    
    try{
        await client.connect()
        const database = client.db('tinderdb')
        const users = database.collection('users')
        const query = { user_id: formData.user_id}

        const updateDocument = {
            $set:{
                first_name: formData.first_name ,
        dob_day: formData.dob_day,
        dob_month: formData.dob_month,
        dob_year: formData.dob_year,
        show_gender: formData.show_gender,
        gender_identity: formData.gender_identity,
        gender_interest: formData.gender_interest,
        url: formData.url,
        about: formData.about,
        matches:formData.matches
            },
        }
const insertedUser= await users.updateOne(query, updateDocument)
res.send(insertedUser)


    }finally{
        await client.close()
    }
})

app.listen(PORT, () => console.log('server running on PORT' + PORT))

dashbord (where the user is giving me null)

import TinderCard from 'react-tinder-card'
import React, { useState ,useEffect } from 'react'
import { useCookies } from 'react-cookie'
import ChatContainer from '../components/ChatContainer'
import axios from 'axios'

const Dashboard = () => {

  const [cookies , setCookie , removeCookie] = useCookies (['user'])
  const [user, setUser] = useState (null)
  
  const userId = cookies.UserId


  const getUser = async () => {
      try {
          const response = await axios.get('http://localhost:8000/user', {
              params: {userId}
          })
          setUser(response.data)
      } catch (error) {
          console.log(error)
      }
  }

  useEffect(() => {
    getUser()

}, [])

  console.log('user', user)/*this is where it coming null*/
 

  const characters = [
    {
      name: 'Richard Hendricks',
      url: 'https://i.imgur.com/7qADjo0.jpg'
    },
    {
      name: 'Erlich Bachman',
      url: 'https://i.imgur.com/7qADjo0.jpg'
    },
    {
      name: 'Monica Hall',
      url: 'https://i.imgur.com/7qADjo0.jpg'
    },
    {
      name: 'Jared Dunn',
      url: 'https://i.imgur.com/7qADjo0.jpg'
    },
    {
      name: 'Dinesh Chugtai',
      url: 'https://i.imgur.com/7qADjo0.jpg'
    }
  ]
  const [lastDirection, setLastDirection] = useState()

  const swiped = (direction, nameToDelete) => {
    console.log('removing: ' + nameToDelete)
    setLastDirection(direction)
  }

  const outOfFrame = (name) => {
    console.log(name + ' left the screen!')
  }

  return (
   <div className="dashboard">
   
      <ChatContainer user={user} />
      <div className="swiper-container">
        <div className="card-container">
          {characters.map((character) =>
            <TinderCard className='swipe'
             key={character.name}
             preventSwipe={["up","down"]}
             onSwipe={(dir) => swiped(dir, character.name)} 
             onCardLeftScreen={() => outOfFrame(character.name)}>
              <div style={{ backgroundImage: 'url(' + character.url + ')' }} 
              className='card'>
              <h3>{character.name}</h3>
              </div>
            </TinderCard>
          )}

        </div>
<div className='swipe-info'>
  {lastDirection ? <p> you swiped {lastDirection}</p> : <p/> }
</div>
      </div>

    </div>
  )

}

export default Dashboard

i know i should narrow down the problem but i'm not sure since i have a little knowlege in back-end i would really apreciate your help and oppinions on what im doing wrong here

  • This error is very common and googling it would've immediately pointed you to the solution. Anyway, you need to check line 84 of index.js, that's where your code is branching wrong and attempting to `res.send` or `res.render` something for the second time (you can only do that once per route handler) –  Aug 09 '22 at 19:49
  • I checked line 84, you need to put `else` at the start –  Aug 09 '22 at 19:50
  • Duplicate: [Error: Can't set headers after they are sent to the client](https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client) –  Aug 09 '22 at 19:51
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Aug 09 '22 at 19:58
  • ChrisG thank you so much this is my first time i posted a question , you were very helpful that did fix the error and it make sense , yet the ` console.log('user', user)` still giving me null do you have any thaughts about that , and again thanks for your help – ZENATI Mohammed el-amine Aug 09 '22 at 20:17

0 Answers0