Javascript Can';在express中使用res.sendFile()时不设置cookie

Javascript Can';在express中使用res.sendFile()时不设置cookie,javascript,node.js,express,Javascript,Node.js,Express,使用res.sendFile()时,响应中不会收到设置cookie头 app.get(sessionTracker, (req, res, next) => { res.cookie('tracker', '123a', { maxAge: 172800000, httpOnly: true, secure: true }); return res.status(200).sendFile(path.join(ROOT_DIR, 'dist', 'ind

使用res.sendFile()时,响应中不会收到设置cookie

app.get(sessionTracker, (req, res, next) => {
  res.cookie('tracker', '123a', {
    maxAge: 172800000,
    httpOnly: true,
    secure: true
  });
  return res.status(200).sendFile(path.join(ROOT_DIR, 'dist', 'index.html')).end();
});
响应

  • @Chandan我能做到这一点,你不需要.end()

  • 还要确保“sessionTracker”变量没有混淆


  • 我也有同样的问题。我以前决定这样做:

    <a href="/redirect-coaching">Coaching</a> 
    
    
    router.get('/redirect-coaching', (req, res) =>
    {
       res.redirect('/coaching')
    })
    
    我知道这有点不对劲。。。但它是有效的,这就决定了曲奇


    如果有人能提供更优雅的解决方案,我将不胜感激。

    试试这个res.set('set-Cookie','mycokie=cookieValue;Path=/')。您使用什么工具查看响应?有没有可能它尊重了
    httpOnly:true,
    ,因此没有向您显示cookie?或者,您可能没有使用https连接来阻止发送cookie。仅供参考,在
    之后没有
    .end()
    。sendfile()
    。由于这是默认状态,因此不需要状态(200)
    。因此,您可以自己执行
    res.sendFile(path.join(ROOT_DIR,'dist','index.html'))
    所有操作。作为一个实验,尝试删除
    httpOnly:true
    secure:true
    以查看它们是否阻止Express发送cookie或阻止您的客户端工具显示cookie。我一开始只尝试了
    res.sendFile(path.join(ROOT\u DIR,'dist',index.html')
    。您更改或修复了什么?您的代码看起来几乎相同。请用文字描述您认为OP的问题是什么。“sessionTracker”是中间件,.end()用于确保响应已结束。无论如何,谢谢你。问题是从开发服务器而不是express服务器提供的文件。只有API请求到达express服务器,但index.html文件来自开发服务器。我删除了.end()并认为这个问题,尽管它不准确,所以我尝试分享对我有用的内容,但@ChandanS很高兴你解决了这个问题。
    <a href="/redirect-coaching">Coaching</a> 
    
    
    router.get('/redirect-coaching', (req, res) =>
    {
       res.redirect('/coaching')
    })
    
    router.get('/coaching', (req, res) =>
    {
       res.sendFile(path.resolve(__dirname, '../views/coaching.html'))
    })