【问题标题】:this set-cookie was blocked because its domain attribute was invalid with regards to the curent host url此 set-cookie 被阻止,因为它的域属性对于当前主机 url 无效
【发布时间】:2021-01-29 16:39:32
【问题描述】:

我有两个带有 reactjs 的应用程序客户端,它们在 (http://localhost:3000) 端口中运行,而服务器端应用程序在 (http://localhost:3001) 端口(express)中运行。 所以我想在用户登录时为包含令牌的 http://localhost:3000 设置 cookie,但我收到了警告

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'))

})

在前端,当用户登录时我有这个获取请求:

  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)})

  }

我认为这个错误是因为我无法将 cookie 设置为不同的域,因为您知道我有两个应用程序在不同的端口上运行。

请帮我解决这个问题。
提前谢谢你。

【问题讨论】:

  • 您可以只运行节点服务器应用程序,而无需单独的反应应用程序服务器。在这种情况下,您应该在包含 react 应用程序的基本路由上返回 res.sendFile('index.html')

标签: node.js reactjs express cookies


【解决方案1】:

如果您真的想在浏览器中设置该 cookie,您应该设置一个有效域,但在您的情况下(“http://localhost:3000”不是有效域),否则只需删除该域即可在浏览器中设置:


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

编码愉快。

【讨论】:

    猜你喜欢
    • 2020-10-26
    • 2020-07-12
    • 2020-12-20
    • 2023-04-09
    • 2022-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多