Cookie 不是使用 axios 保存在浏览器中,而是保存在 Insomnia 中

问题描述

我有一个应用程序,它使用 Reactjs 作为客户端,使用 node express 作为服务器端。 我在服务器的标题中发送烹饪,cookie 显示在浏览器中,但没有保存,但保存了我使用 Insomnia 我已经阅读了很多关于此的问题和答案,但实际上并没有解决问题。 下面是我的设置

** 客户端示例代码 ----------- **

 export const BusinessLogin = (header,account) => axios.post(`${businessURI}/login`,account,header) // 

export const LoginBusiness = (account) => async (dispatch) => {
    const config = {
        headers :{
            'Content-Type': 'application/json'
        },credentials: "include",withCredentials: true
    }
    try {
        const  data  = await api.BusinessLogin(config,account)
        console.log(data)
        dispatch({type:LOGIN_BUSInesS,payload: data })
        console.log(data)
    } catch (error) {

        console.log(error.message)
    }

}

** 服务器端索引文件----------- **

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

app.use(function(req,res,next) {
    //client is hosted at '127.0.0.1:3000'
    res.header('Access-Control-Allow-Origin','127.0.0.1:3000');
    //  res.header('XMLHTTPRequest','http://127.0.0.1:3000/')
    res.header('Access-Control-Allow-Credentials',true);
    res.header('Access-Control-Allow-Methods','GET,POST,PUT,DELETE,OPTIONS')
    res.setHeader('Access-Control-Expose-Headers','x-pagination,Content-Length');
    res.header('Access-Control-Allow-Headers','Origin,X-Requested-With,Content-Type,Accept');
    next();
  });

  import business from './routes/business.js';
  app.use('/buss',business)

// Libraries 
import cors from 'cors';
import cookieParser from 'cookie-parser'

** 服务器端路由器文件----------- **

  // different libries tried 
 import cookieParser from 'cookie-parser'
 import cookie from 'cookie'

export const Login = async (req,res) => {
      
    const {email,password} = req.body; 
    const new_account = req.body; 
    const {cookies} = req
   //  console.log("cookies",req.sessionStore)
     console.log("cookies",req.cookies)
    //  console.log(req)
     const  test_cookies = cookie.parse(req.headers.cookie || '');
     console.log(test_cookies)
 
    //  console.log( req)
    if(!email || !password ) return res.status(400).json('fill all field') 
    
    try {
        await CreateBusiness.findOne({email})
        .then(account => {
            
            if(!account) return res.status(400).json({msg:"The email or password you enter does not match account"})
            //Validate password with  exiting password 
            bcrypt.compare(password,account.password) 
              .then(isMatch => {
             
                  if(!isMatch) return res.status(400).json({msg: "invalid credentials "})
              //user match,jwt.sign(
                { id: account._id },Jwt_secret,{ expiresIn: 3600 },//last for hour
                (error,token) => {
                    if(error) throw error;
                    
                    const cookies = {
                        maxAge: 3600,httpOnly: false,sameSite:false,// secure: true // activate during deployment
                    }
                    // trying different methods of setting cookis
                     res.cookie('accesstoken','474949',cookies)
                    res.setHeader('Content-Type','text/html; charset=UTF-8');
                    res.setHeader('Access-Control-Allow-Credentials','true')
                    res.setHeader('Set-Cookie',cookie.serialize('name','just tetsing the cooki',{
                        httpOnly: true,maxAge: 60 * 60 * 24 * 7 // 1 week
                      }));
                    res.status(201).cookie('access_token','Bearer ' + token,cookies)
                    res.json({
                        token,})
                    // res.status(200).json(res)
                }
            )
       
        })
    })
   
    } catch (error) {
        res.status(209).json({message: error.message})

    }
   
}  

我尝试过的其他事情

在阅读了类似的问题后,有些人建议设置 //axios.defaults.withCredentials = true, 但每次我都会有一个 cors 错误,即使我已经按如下所示进行了 cors 配置,尽管我在配置中添加withCredentials: true。 我也使用过这个 cors extension,但 cookie 仍然没有保存在浏览器中。

您认为是什么导致他们无法保存,我该如何解决? 感谢您抽出宝贵时间。

解决方法

在服务器上设置 cookie 时将 sameSite 设置为“lax”。如果设置为“无”,则除非 cookie 还具有“安全”属性,否则它将不起作用。这是由浏览器强制执行的。

Insmonia 和其他 REST 客户端不关心这个。

Source

res.cookie('accessToken',foo,{
    maxAge: 3600,sameSite: "lax",path: "/",});

此外,请确保在发出提取请求时传递 credentials: 'include',我可以看到您正在这样做。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...