【问题标题】:Cookies are not saving in browser using axios but they are saved in InsomniaCookies 没有使用 axios 保存在浏览器中,但它们保存在 Insomnia 中
【发布时间】:2021-04-09 17:01:36
【问题描述】:

我有一个使用 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,
                        account, 
                    })
                    // 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没有保存在浏览器中的主要原因是我的服务器运行在localhost:7000,而我的前端是127.0.0.1:3000,这使得它们不同的域.解决这个问题,我只是让我的前端在localhost:3000 运行,问题就解决了

标签: cookies http-headers session-cookies httpcookie cookie-httponly


【解决方案1】:

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

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

Source

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

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

【讨论】:

    猜你喜欢
    • 2020-08-24
    • 1970-01-01
    • 2017-06-30
    • 2022-12-23
    • 2022-11-02
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多