salah
salah

Reputation: 73

this set-cookie was blocked because its domain attribute was invalid with regards to the curent host url

i have two app client-side with reactjs which running in (http://localhost:3000) port and server-side app which running in (http://localhost:3001) port (express). so i want to set cookie for the http://localhost:3000 which contain the token when the user login,but i got the warning

this set-cookie was blocked because its domain attribute was invalid with regards to the curent host url 

see the picture Response Headers

server.js :

//signIn
app.post('/Signin',(req,res,next)=>{
    const {email,password}=req.body;
    db.select('email','hash').from('signin')
    .where('email','=',email)
    .then(data=>{
        const isValide=bcrypt.compareSync(password, data[0].hash);
        if(isValide){
            return db.select('*')
            .from('users')
            .where('email','=',email)
            .then(
                user=>{ 
                    // res.json(user[0]);

                    jwt.sign({user:user[0]},secretkey,(err,token)=>{ 
 
                   
                     res.cookie('user', token,  { domain: 'http://localhost:3000',
                      httpOnly:true ,expire: Date.now()+ 36000}).
                     status(200).json({token: token});
                    })
                


            }).catch(err=>res.status(400).json('unable to get user'))
        
        }else{
            res.status(400).json('wrong credentials')
        }
    }).catch(err=>res.status(400).json('wrong credentials'))

})

in the front-end i have this fetch request when user signin:

  handleSubmit = (e) => {
    const {email,password}=this.state;
    e.preventDefault();
    // this.props.signin(this.state);
   fetch('http://localhost:3001/Signin',{
    method:'post',
        headers:{'Content-Type':'application/json'},
        credentials: 'include',
        body:JSON.stringify({
            email:email,
            password:password   
     })

  }).then(response=>response.json())
  .then(token=>{
    console.log(token);
  })
  .catch(err=>{console.log(err)})

  }

i think this error because i can't set cookie to a different domain as you know i have two apps running on a different port.

please please help me to solve this problem.
thank you in advance.

Upvotes: 3

Views: 8472

Answers (1)

Salah
Salah

Reputation: 622

if you are really want to set that cookie in the browser you should set a valid domain, but in your case("http://localhost:3000" is not a valid domain) otherwise just remove that domain and it will set in the browser :


                     res.cookie('user', token,  { 
                      httpOnly:true ,expire: Date.now()+ 36000}).
                     status(200).json({token: token});

Happy coding.

Upvotes: 4

Related Questions