Cors-关于当前主机网址,此set-cookie域属性无效 [英] Cors - This set-cookie domain attribute was invalid with regards to the current host url

查看:576
本文介绍了Cors-关于当前主机网址,此set-cookie域属性无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个节点后端,该节点应允许运行在localhost:3000上的前端应用程序发出跨源请求.因此,我将cors政策限制在我的域内.

I have a node backend, which should allow cross origin request from my frontend application that is running on localhost:3000. Therefore I've restricted the cors policy to my domain.

import csrf from 'csurf';

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

const csrfProtection = csrf({
  cookie: {
    maxAge: 900,
    domain: 'http://localhost:3000'
  }
})

router.get('/csrfToken', csrfProtection, async (req, res, next) => {
  res.json({ token: req.csrfToken() });
});

当我现在向服务器端点(在localhost:5000上运行)发出请求时,它向我返回以下错误,提示无法设置cookie.

When I'm making now a request to my server endpoint (which is running on localhost:5000), it returns me the following error that the cookie cannot be set.

  fetch('http://localhost:5000/csrfToken', {
      method: 'GET',
      credentials: 'include'
 })

推荐答案

这与CORS无关.这就是cookie的工作方式.

This has nothing to do with CORS. It is just how cookies work.

set-cookie 标头中的域为 http://localhost:3000 ,但请求是针对 http://localhost:5000 .

The domain in the set-cookie header says http://localhost:3000 but the request is for http://localhost:5000.

这是一个不同的来源,无效的cookie也是如此.

That is a different origin and so is an invalid cookie.

一个来源的 set-cookie 标头不可能为其他来源设置cookie. http://localhost:5000 只能为 http://localhost:5000 设置cookie.

It is impossible for a set-cookie header from one origin to set a cookie for a different origin. http://localhost:5000 can only set cookies for http://localhost:5000.

如果您真的想为:3000 设置cookie,则一种解决方法是通过cookie以外的其他格式(例如,在请求正文中)提供数据,然后使用 http://localhost:3000 上的客户端JS使用 document.cookie API .

If you really want to set a cookie for :3000 then a work-around would be to provide the data through some other format than a cookie (e.g. in the request body) and then have the client-side JS on http://localhost:3000 set the cookie using the document.cookie API.

如果您想为:5000 设置cookie(这似乎更有可能),则在 set-cookie 标头中获取端口号.

If you want to set the cookie for :5000 (which seems more likely), then get the port number right in the set-cookie header.

const csrfProtection = csrf({
  cookie: {
    maxAge: 900,
    domain: 'http://localhost:5000'
  }
})

这篇关于Cors-关于当前主机网址,此set-cookie域属性无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆