当我尝试从端口 3000 获取它们时,为什么我的 cookie 和 signedCookies 在 req 中是空的?

Why are my cookies and signedCookies empty in req when I try to get them from port 3000?

当我想使用 express 从 get 请求中检索会话 cookie 时遇到问题。

我的服务器 运行 在端口 8000 上,而我的应用程序 运行 在端口 3000 上。

当我直接继续 http://localhost:8000/setcookie 和 /getcookie 时,我可以获取和设置 cookie,并且工作正常。 另一方面,当我从 http://localhost:3000 尝试相同的事情并使用 axios 在端口 8000 上获取或 post 请求时,请求中的 cookies 和 signedCookies 为空,我不知道为什么。是因为我从3000端口发送它,即使我正在监听并向端口8000发送请求吗?

我尝试使用 get 和 post 方法来创建 cookie。他们似乎都没有工作。我有点迷路了。

希望我的解释足够清楚,非常感谢!

服务器

const app = express()
const port = process.env.PORT || 8000
app.set("port", port)

const http = require('http').Server(app);

//Body Parser
var urlencodedParser = bodyParser.urlencoded({
    extended: true
});
app.use(urlencodedParser);
app.use(bodyParser.json());

//Définition des CORS
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

app.use(cookieParser("secret")); 

app.get('/setcookie', function (req, res, next) {
  // Update views
  console.log("connection", req);
  var mail = req.body.email
  res.cookie('b', 'jefaisuntest', {signed: true, expire : 600000});

  // Write response
  res.send("cookie sent")
})

app.get('/getcookie', function(req, res) {
    var username = req.signedCookies['b'];

    console.log("iciiii", req)
    if (username) {
        return res.send(username);
    }

    return res.send('No cookie found');
});

const server = http.listen(port, function () {
    console.log(`listening on *:${port}`)
})

客户

import axios from 'axios';

const headers = {
    'Content-Type': 'application/json'
}
const burl = "http://localhost:8000"

export default {
    login : function(email:string, password:string) {
        axios.get(burl + '/setcookie')
    },
    isAuth : function() {
        axios.get(burl + '/getcookie')
    },
}

每个 host:port 组合都是一个不同的网站。您不能在两个不同的 "domains"

之间共享 cookie

@mnesarco 所说的是正确的 - 从技术上讲,您是 运行 两个不同的服务器,这意味着您在两者之间发送的任何请求都是 CORS 请求。为了在 CORS 请求中共享发送 cookie,您需要将 withCredentials 标志设置为 true:

export default {
    login : function(email:string, password:string) {
        axios.get(burl + '/setcookie', { withCredentials: true })
    },
    isAuth : function() {
        axios.get(burl + '/getcookie', { withCredentials: true })
    },
}

有关详细信息,请参阅 from a similar situation or this mdn page